2016-04-27 64 views
0

我对Python非常陌生,在从类的属性中删除重复值时遇到了一些麻烦(我认为这是正确的术语)。从类变量的属性中删除重复对象

具体而言,我想删除同一年的每个值。我应该注意到,我只打印前四个值并搜索前四个值。属性中的数据实际上是以Yearmonthday格式(例如:19070101是1907年1月的第一个)。

不管怎么说,这里是我的代码:

import csv 
import os 

class Datatype: 
    'Data from the weather station' 
    def __init__ (self, inputline): 
     [ self.DATE, 
      self.PRCP] = inputline.split(',') 


filename ='LAWe.txt' 
LAWd = open(filename, 'r') 
LAWefile = LAWd.read() 
LAWd.close() 

'Recognize the line endings for MS-DOS, UNIX, and Mac and apply the .split() method to the string wholeFile' 
if '\r\n' in LAWefile: 
    filedat = LAWefile.split('\r\n')  # the split method, applied to a string, produces a list 
elif '\r' in LAWefile: 
    filedat = LAWefile.split('\r') 
else: 
    filedat = LAWefile.split('\n') 


collection = dict() 
date= dict() 
for thisline in filedat: 
    thispcp = Datatype(thisline)     # here is where the Datatype object is created (running the __init__ function) 
    collection[thispcp.DATE] = thispcp  # the dictionary will be keyed by the ID attribute 
for thisID in collection.keys(): 
    studyPRP = collection[thisID] 
    if studyPRP.DATE.isdigit(): 
     list(studyPRP.DATE)   
     if len(date[studyPRP.DATE][0:4]): 
      pass       #if year is seen once, then skip and go to next value in attribute 
     else: 
      print studyPRP.DATE[0:4]  #print value in this case the year) 
      date[studyPRP.DATE]=studyPRP.DATE[0:4] 

我得到这个错误:

回溯(最后最近一次调用): 文件 “project.py” 61行,在 如果len(date [studyPRP.DATE] [0:4]): KeyError:'19770509'

可以修复一个关键错误(这意味着一个值不在列表中,但它是用于我的数据)通过使用设置功能(或者我读过),但我有30,000件我正在处理的信息,似乎你必须手动输入信息,所以这不适合我。

任何帮助都将不胜感激

很抱歉,如果这是令人困惑的或无意义的,因为我感到非常新的Python。

+2

那么什么是数据类型? 'filedat'中有什么?请给[mcve],否则没人能帮忙。 – jonrsharpe

+0

我编辑了包含该信息的代码。感谢您的回应。 – Preston

+0

注*最小*,并给予完整的追溯。 – jonrsharpe

回答

0

替换此

if len(date[studyPRP.DATE][0:4]) 

if len(date[studyPRP.DATE[0:4]]): 

说明:

  • 在您选择整个日期作为关键KeyError: '19770509'中的4个第一项的第一行日期
  • 在修正中您sen d字典中的日期(年份)的前4个字符
0

不知道你到底想要什么。我会回复,我可以帮你什么。

您的错误是因为您在添加之前正在访问您的年份data

此外,什么要添加到您的收藏就像是

{ 
    <object>.DATE: <object> 
} 

我不知道什么您这里需要。你的下for loop可以写为下:

for thisID in collection: 
    if thisID.isdigit(): 
     if thisID[0:4] in date and len(date[thisID[0:4]]): 
      #if year is seen once, then skip and go to next 
      # value in attribute 
      pass 
     else: 
      print thisID[0:4]  #print value in this case the year) 
      date[thisID[0:4]]=thisID[0:4] 

注意你的studyPRP.DATE是一样thisID