99999久久久久久亚洲,欧美人与禽猛交狂配,高清日韩av在线影院,一个人在线高清免费观看,啦啦啦在线视频免费观看www

熱線電話:13121318867

登錄
首頁精彩閱讀在python的類中動態(tài)添加屬性與生成對象
在python的類中動態(tài)添加屬性與生成對象
2017-08-17
收藏

python的類中動態(tài)添加屬性與生成對象

本文將通過一下幾個方面來一一進(jìn)行解決
      1、程序的主要功能
      2、實(shí)現(xiàn)過程
      3、類的定義
      4、用生成器generator動態(tài)更新每個對象并返回對象
      5、使用strip 去除不必要的字符
      6、rematch匹配字符串
      7、使用timestrptime提取字符串轉(zhuǎn)化為時間對象
     8、完整代碼

程序的主要功能

現(xiàn)在有個存儲用戶信息的像表格一樣的文檔:第一行是屬性,各個屬性用逗號(,)分隔,從第二行開始每行是各個屬性對應(yīng)的值,每行代表一個用戶。如何實(shí)現(xiàn)讀入這個文檔,每行輸出一個用戶對象呢?
另外還有4個小要求:

每個文檔都很大,如果一次性把所有行生成的那么多對象存成列表返回,內(nèi)存會崩潰。程序中每次只能存一個行生成的對象。

用逗號隔開的每個字符串,前后可能有雙引號(”)或者單引號('),例如”張三“,要把引號去掉;如果是數(shù)字,有+000000001.24這樣的,要把前面的+和0都去掉,提取出1.24

文檔中有時間,形式可能是2013-10-29,也可能是2013/10/29 2:23:56 這樣的形式,要把這樣的字符串轉(zhuǎn)成時間類型

這樣的文檔有好多個,每個的屬性都不一樣,例如這個是用戶的信息,那個是通話紀(jì)錄。所以類中的具體屬性有哪些要根據(jù)文檔的第一行動態(tài)生成

實(shí)現(xiàn)過程

1.類的定義

由于屬性是動態(tài)添加的,屬性-值 對也是動態(tài)添加的,類中要含有updateAttributes()和updatePairs()兩個成員函數(shù)即可,此外用列表attributes存儲屬性,詞典attrilist存儲映射。其中init()函數(shù)為構(gòu)造函數(shù)。 __attributes前有下劃線表示私有變量,不能在外面直接調(diào)用。實(shí)例化時只需a=UserInfo()即可,無需任何參數(shù)。
    
class UserInfo(object):
 'Class to restore UserInformation'
 def __init__ (self):
  self.attrilist={}
  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]

2.用生成器(generator)動態(tài)更新每個對象并返回對象

生成器相當(dāng)于一個只需要初始化一次,就可自動運(yùn)行多次的函數(shù),每次循環(huán)返回一個結(jié)果。不過函數(shù)用return 返回結(jié)果,而生成器用yield 返回結(jié)果。每次運(yùn)行都在yield返回,下一次運(yùn)行從yield之后開始。例如,我們實(shí)現(xiàn)斐波拉契數(shù)列,分別用函數(shù)和生成器實(shí)現(xiàn):    
def fib(max):
 n, a, b = 0, 0, 1
 while n < max:
  print(b)
  a, b = b, a + b
  n = n + 1
 return 'done'

我們計(jì)算數(shù)列的前6個數(shù):
    
>>> fib(6)
1
1
2
3
5
8
'done'

如果用生成器的話,只要把 print 改成 yield 就可以了。如下:
    
def fib(max):
 n, a, b = 0, 0, 1
 while n < max:
  yield b
  a, b = b, a + b
  n = n + 1

使用方法:    
>>> f = fib(6)
>>> f
<generator object fib at 0x104feaaa0>
>>> for i in f:
...  print(i)
...
1
1
2
3
5
8
>>>

可以看到,生成器fib本身是個對象,每次執(zhí)行到y(tǒng)ield會中斷返回一個結(jié)果,下次又繼續(xù)從yield的下一行代碼繼續(xù)執(zhí)行。生成器還可以用generator.next()執(zhí)行。

在我的程序中,生成器部分代碼如下:
    
def ObjectGenerator(maxlinenum):
 filename='/home/thinkit/Documents/usr_info/USER.csv'
 attributes=[]
 linenum=1
 a=UserInfo()
 file=open(filename)
 while linenum < 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

其中,a=UserInfo()為類UserInfo的實(shí)例化.因?yàn)槲臋n是gb2312編碼的,上面使用了對應(yīng)的解碼方法。由于第一行是屬性,有個函數(shù)將屬性列表存入U(xiǎn)serInfo中,即updateAttributes();后面的行則要將 屬性-值 對讀入一個字典中存儲。p.s.python中的字典相當(dāng)于映射(map).

3.使用strip 去除不必要的字符

從上面代碼中,可以看到使用str.strip(somechar)即可去除str前后的somechar字符。somechar可以是符號,也可以是正則表達(dá)式,如上:    
item=item.strip()#除去字符串前后的所有轉(zhuǎn)義字符,如\t,\n等
item=item.strip('\"')#除去前后的"
item=item.strip('\'')
item=item.strip('+0*')#除去前后的+00...00,*表示0的個數(shù)可以任意多,也可以沒有

4.re.match匹配字符串

函數(shù)語法:    
re.match(pattern, string, flags=0)

函數(shù)參數(shù)說明:

參數(shù)           描述

pattern       匹配的正則表達(dá)式

string         要匹配的字符串。

flags          標(biāo)志位,用于控制正則表達(dá)式的匹配方式,如:是否區(qū)分大小寫,多行匹配等等。

若匹配成功re.match方法返回一個匹配的對象,否則返回None。`

>>> s='2015-09-18'
>>> matchObj=re.match(r'\d{4}-\d{2}-\d{2}',s, flags= 0)
>>> print matchObj
<_sre.SRE_Match object at 0x7f3525480f38>
5.使用time.strptime提取字符串轉(zhuǎn)化為時間對象

在time模塊中,time.strptime(str,format)可以把str按照format格式轉(zhuǎn)化為時間對象,format中的常用格式有:

     %y 兩位數(shù)的年份表示(00-99)

     %Y 四位數(shù)的年份表示(000-9999)

     %m 月份(01-12)

     %d 月內(nèi)中的一天(0-31)

     %H 24小時制小時數(shù)(0-23)

     %I 12小時制小時數(shù)(01-12)

     %M 分鐘數(shù)(00=59)

     %S 秒(00-59)

此外,還需要使用re模塊,用正則表達(dá)式,對字符串進(jìn)行匹配,看是否是一般時間的格式,如YYYY/MM/DD H:M:S, YYYY-MM-DD等

在上面的代碼中,函數(shù)catchTime就是判斷item是否為時間對象,是的話轉(zhuǎn)化為時間對象。

代碼如下:    
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}\s\d+:\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}\s\d+:\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 < 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  #輸出字典,看是否正確
總結(jié)
以上就是這篇文章的全部內(nèi)容,希望能對大家的學(xué)習(xí)或者工作帶來一定幫助

數(shù)據(jù)分析咨詢請掃描二維碼

若不方便掃碼,搜微信號:CDAshujufenxi

數(shù)據(jù)分析師資訊
更多

OK
客服在線
立即咨詢
客服在線
立即咨詢
') } function initGt() { var handler = function (captchaObj) { captchaObj.appendTo('#captcha'); captchaObj.onReady(function () { $("#wait").hide(); }).onSuccess(function(){ $('.getcheckcode').removeClass('dis'); $('.getcheckcode').trigger('click'); }); window.captchaObj = captchaObj; }; $('#captcha').show(); $.ajax({ url: "/login/gtstart?t=" + (new Date()).getTime(), // 加隨機(jī)數(shù)防止緩存 type: "get", dataType: "json", success: function (data) { $('#text').hide(); $('#wait').show(); // 調(diào)用 initGeetest 進(jìn)行初始化 // 參數(shù)1:配置參數(shù) // 參數(shù)2:回調(diào),回調(diào)的第一個參數(shù)驗(yàn)證碼對象,之后可以使用它調(diào)用相應(yīng)的接口 initGeetest({ // 以下 4 個配置參數(shù)為必須,不能缺少 gt: data.gt, challenge: data.challenge, offline: !data.success, // 表示用戶后臺檢測極驗(yàn)服務(wù)器是否宕機(jī) new_captcha: data.new_captcha, // 用于宕機(jī)時表示是新驗(yàn)證碼的宕機(jī) product: "float", // 產(chǎn)品形式,包括:float,popup width: "280px", https: true // 更多配置參數(shù)說明請參見:http://docs.geetest.com/install/client/web-front/ }, handler); } }); } function codeCutdown() { if(_wait == 0){ //倒計(jì)時完成 $(".getcheckcode").removeClass('dis').html("重新獲取"); }else{ $(".getcheckcode").addClass('dis').html("重新獲取("+_wait+"s)"); _wait--; setTimeout(function () { codeCutdown(); },1000); } } function inputValidate(ele,telInput) { var oInput = ele; var inputVal = oInput.val(); var oType = ele.attr('data-type'); var oEtag = $('#etag').val(); var oErr = oInput.closest('.form_box').next('.err_txt'); var empTxt = '請輸入'+oInput.attr('placeholder')+'!'; var errTxt = '請輸入正確的'+oInput.attr('placeholder')+'!'; var pattern; if(inputVal==""){ if(!telInput){ errFun(oErr,empTxt); } return false; }else { switch (oType){ case 'login_mobile': pattern = /^1[3456789]\d{9}$/; if(inputVal.length==11) { $.ajax({ url: '/login/checkmobile', type: "post", dataType: "json", data: { mobile: inputVal, etag: oEtag, page_ur: window.location.href, page_referer: document.referrer }, success: function (data) { } }); } break; case 'login_yzm': pattern = /^\d{6}$/; break; } if(oType=='login_mobile'){ } if(!!validateFun(pattern,inputVal)){ errFun(oErr,'') if(telInput){ $('.getcheckcode').removeClass('dis'); } }else { if(!telInput) { errFun(oErr, errTxt); }else { $('.getcheckcode').addClass('dis'); } return false; } } return true; } function errFun(obj,msg) { obj.html(msg); if(msg==''){ $('.login_submit').removeClass('dis'); }else { $('.login_submit').addClass('dis'); } } function validateFun(pat,val) { return pat.test(val); }