在python的类中动态添加属性与生成对象
gt;gt;gt; s='2015-09-18' 5.使用time.strptime提取字符串转化为时间对象 在 nbsp;nbsp;nbsp;nbsp; %y 两位数的年份表示(00-99) nbsp;nbsp;nbsp;nbsp; %Y 四位数的年份表示(000-9999) nbsp;nbsp;nbsp;nbsp; %m 月份(01-12) nbsp;nbsp;nbsp;nbsp;nbsp;%d 月内中的一天(0-31) nbsp;nbsp;nbsp;nbsp; %H 24小时制小时数(0-23) nbsp;nbsp;nbsp;nbsp; %I 12小时制小时数(01-12) nbsp;nbsp;nbsp;nbsp; %M 分钟数(00=59) nbsp;nbsp;nbsp;nbsp; %S 秒(00-59) 此外,还需要使用 在上面的代码中,函数catchTime就是判断item是否为时间对象,是的话转化为时间对象。 代码如下: import time import re def catchTime(item): # check if it's time matchObj=re.match(r'd{4}-d{2}-d{2}',item, flags= 0) if matchObj!= None : item =time.strptime(item,'%Y-%m-%d') #print "returned time: %s " %item return item else: matchObj=re.match(r'd{4}/d{2}/d{2}sd+:d+:d+',item,flags=0 ) if matchObj!= None : item =time.strptime(item,'%Y/%m/%d %H:%M:%S') #print "returned time: %s " %item return item 完整代码: import collections import time import re class UserInfo(object): 'Class to restore UserInformation' def __init__ (self): self.attrilist=collections.OrderedDict()# ordered self.__attributes=[] def updateAttributes(self,attributes): self.__attributes=attributes def updatePairs(self,values): for i in range(len(values)): self.attrilist[self.__attributes[i]]=values[i] def catchTime(item): # check if it's time matchObj=re.match(r'd{4}-d{2}-d{2}',item, flags= 0) if matchObj!= None : item =time.strptime(item,'%Y-%m-%d') #print "returned time: %s " %item return item else: matchObj=re.match(r'd{4}/d{2}/d{2}sd+:d+:d+',item,flags=0 ) if matchObj!= None : item =time.strptime(item,'%Y/%m/%d %H:%M:%S') #print "returned time: %s " %item return item def ObjectGenerator(maxlinenum): filename='/home/thinkit/Documents/usr_info/USER.csv' attributes=[] linenum=1 a=UserInfo() file=open(filename) while linenum lt; maxlinenum: values=[] line=str.decode(file.readline(),'gb2312')#linecache.getline(filename, linenum,'gb2312') if line=='': print'reading fail! Please check filename!' break str_list=line.split(',') for item in str_list: item=item.strip() item=item.strip('"') item=item.strip(''') item=item.strip('+0*') item=catchTime(item) if linenum==1: attributes.append(item) else: values.append(item) if linenum==1: a.updateAttributes(attributes) else: a.updatePairs(values) yield a.attrilist #change to ' a ' to use linenum = linenum +1 if __name__ == '__main__': for n in ObjectGenerator(10): print n #输出字典,看是否正确 总结 以上就是这篇文章的全部内容,希望能对大家的学习或者工作带来一定帮助,如果有疑问大家可以留言交流,谢谢大家对脚本之家的支持。 (编辑:淮北站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |