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

熱線電話:13121318867

登錄
首頁精彩閱讀Python用list或dict字段模式讀取文件的方法
Python用list或dict字段模式讀取文件的方法
2018-02-21
收藏

Python用list或dict字段模式讀取文件的方法

Python用于處理文本數(shù)據(jù)絕對是個利器,極為簡單的讀取、分割、過濾、轉(zhuǎn)換支持,使得開發(fā)者不需要考慮繁雜的流文件處理過程(相對于JAVA來說的,嘻嘻)。博主自己工作中,一些復(fù)雜的文本數(shù)據(jù)處理計算,包括在HADOOP上編寫Streaming程序,均是用Python完成。

而在文本處理的過程中,將文件加載內(nèi)存中是第一步,這就涉及到怎樣將文件中的某一列映射到具體的變量的過程,最最愚笨的方法,就是按照字段的下標進行引用,比如這樣子:

# fields是讀取了一行,并且按照分隔符分割之后的列表
user_id=fields[0]
user_name=fields[1]
user_type=fields[2]

如果按照這種方式讀取,一旦文件有順序、增減列的變動,代碼的維護是個噩夢,這種代碼一定要杜絕。

本文推薦兩種優(yōu)雅的方式來讀取數(shù)據(jù),都是先配置字段模式,然后按照模式讀取,而模式則有字典模式和列表模式兩種形式;

讀取文件,按照分隔符分割成字段數(shù)據(jù)列表

首先讀取文件,按照分隔符分割每一行的數(shù)據(jù),返回字段列表,以便后續(xù)處理。

代碼如下:


defread_file_data(filepath):
 '''根據(jù)路徑按行讀取文件, 參數(shù)filepath:文件的絕對路徑
 @param filepath: 讀取文件的路徑
 @return: 按\t分割后的每行的數(shù)據(jù)列表
 '''
 fin=open(filepath,'r')
 forlineinfin:
  try:
   line=line[:-1]
   ifnotline:continue
  except:
   continue
   
  try:
   fields=line.split("\t")
  except:
   continue
  # 拋出當前行的分割列表
  yieldfields
 fin.close()

使用yield關(guān)鍵字,每次拋出單個行的分割數(shù)據(jù),這樣在調(diào)度程序中可以用for fields in read_file_data(fpath)的方式讀取每一行。

映射到模型之方法1:使用配置好的字典模式,裝配讀取的數(shù)據(jù)列表

這種方法配置一個{“字段名”: 字段位置}的字典作為數(shù)據(jù)模式,然后按照該模式裝配讀取的列表數(shù)據(jù),最后實現(xiàn)用字典的方式訪問數(shù)據(jù)。

所使用的函數(shù):

@staticmethod
defmap_fields_dict_schema(fields, dict_schema):
 """根據(jù)字段的模式,返回模式和數(shù)據(jù)值的對應(yīng)值;例如 fields為['a','b','c'],schema為{'name':0, 'age':1},那么就返回{'name':'a','age':'b'}
 @param fields: 包含有數(shù)據(jù)的數(shù)組,一般是通過對一個Line String通過按照\t分割得到
 @param dict_schema: 一個詞典,key是字段名稱,value是字段的位置;
 @return: 詞典,key是字段名稱,value是字段
 """
 pdict={}
 forfstr, findexindict_schema.iteritems():
  pdict[fstr]=str(fields[int(findex)])
 returnpdict

有了該方法和之前的方法,可以用以下的方式讀取數(shù)據(jù):

# coding:utf8
"""
@author: www.crazyant.net
測試使用字典模式加載數(shù)據(jù)列表
優(yōu)點:對于多列文件,只通過配置需要讀取的字段,就能讀取對應(yīng)列的數(shù)據(jù)
缺點:如果字段較多,每個字段的位置配置,較為麻煩
"""
importfile_util
importpprint
  
# 配置好的要讀取的字典模式,可以只配置自己關(guān)心的列的位置
dict_schema={"userid":0,"username":1,"usertype":2}
forfieldsinfile_util.FileUtil.read_file_data("userfile.txt"):
 # 將字段列表,按照字典模式進行映射
 dict_fields=file_util.FileUtil.map_fields_dict_schema(fields, dict_schema)
 pprint.pprint(dict_fields)

輸出結(jié)果:

{'userid':'1','username':'name1','usertype':'0'}
{'userid':'2','username':'name2','usertype':'1'}
{'userid':'3','username':'name3','usertype':'2'}
{'userid':'4','username':'name4','usertype':'3'}
{'userid':'5','username':'name5','usertype':'4'}
{'userid':'6','username':'name6','usertype':'5'}
{'userid':'7','username':'name7','usertype':'6'}
{'userid':'8','username':'name8','usertype':'7'}
{'userid':'9','username':'name9','usertype':'8'}
{'userid':'10','username':'name10','usertype':'9'}
{'userid':'11','username':'name11','usertype':'10'}
{'userid':'12','username':'name12','usertype':'11'}

映射到模型之方法2:使用配置好的列表模式,裝配讀取的數(shù)據(jù)列表

如果需要讀取文件所有列,或者前面的一些列,那么配置字典模式優(yōu)點復(fù)雜,因為需要給每個字段配置索引位置,并且這些位置是從0開始完后數(shù)的,屬于低級勞動,需要消滅。

列表模式應(yīng)命運而生,先將配置好的列表模式轉(zhuǎn)換成字典模式,然后按字典加載就可以實現(xiàn)。

轉(zhuǎn)換模式,以及用按列表模式讀取的代碼:

@staticmethod
deftransform_list_to_dict(para_list):
 """把['a', 'b']轉(zhuǎn)換成{'a':0, 'b':1}的形式
 @param para_list: 列表,里面是每個列對應(yīng)的字段
 @return: 字典,里面是字段名和位置的映射
 """
 res_dict={}
 idx=0
 whileidx <len(para_list):
  res_dict[str(para_list[idx]).strip()]=idx
  idx+=1
 returnres_dict
  
@staticmethod
defmap_fields_list_schema(fields, list_schema):
 """根據(jù)字段的模式,返回模式和數(shù)據(jù)值的對應(yīng)值;例如 fields為['a','b','c'],schema為{'name', 'age'},那么就返回{'name':'a','age':'b'}
 @param fields: 包含有數(shù)據(jù)的數(shù)組,一般是通過對一個Line String通過按照\t分割得到
 @param list_schema: 列名稱的列表list
 @return: 詞典,key是字段名稱,value是字段
 """
 dict_schema=FileUtil.transform_list_to_dict(list_schema)
 returnFileUtil.map_fields_dict_schema(fields, dict_schema)

使用的時候,可以用列表的形式配置模式,不需要配置索引更加簡潔:

# coding:utf8
"""
@author: www.crazyant.net
測試使用列表模式加載數(shù)據(jù)列表
優(yōu)點:如果讀取所有列,用列表模式只需要按順序?qū)懗龈鱾€列的字段名就可以
缺點:不能夠只讀取關(guān)心的字段,需要全部讀取
"""
importfile_util
importpprint
  
# 配置好的要讀取的列表模式,只能配置前面的列,或者所有咧
list_schema=["userid","username","usertype"]
forfieldsinfile_util.FileUtil.read_file_data("userfile.txt"):
 # 將字段列表,按照字典模式進行映射
 dict_fields=file_util.FileUtil.map_fields_list_schema(fields, list_schema)
 pprint.pprint(dict_fields)

運行結(jié)果和字典模式的完全一樣。

file_util.py全部代碼

以下是file_util.py中的全部代碼,可以放在自己的公用類庫中使用

# -*- encoding:utf8 -*-
'''
@author: www.crazyant.net
@version: 2014-12-5
'''
  
classFileUtil(object):
 '''文件、路徑常用操作方法
 '''
 @staticmethod
 defread_file_data(filepath):
  '''根據(jù)路徑按行讀取文件, 參數(shù)filepath:文件的絕對路徑
  @param filepath: 讀取文件的路徑
  @return: 按\t分割后的每行的數(shù)據(jù)列表
  '''
  fin=open(filepath,'r')
  forlineinfin:
   try:
    line=line[:-1]
    ifnotline:continue
   except:
    continue
    
   try:
    fields=line.split("\t")
   except:
    continue
   # 拋出當前行的分割列表
   yieldfields
  fin.close()
  
 @staticmethod
 deftransform_list_to_dict(para_list):
  """把['a', 'b']轉(zhuǎn)換成{'a':0, 'b':1}的形式
  @param para_list: 列表,里面是每個列對應(yīng)的字段
  @return: 字典,里面是字段名和位置的映射
  """
  res_dict={}
  idx=0
  whileidx <len(para_list):
   res_dict[str(para_list[idx]).strip()]=idx
   idx+=1
  returnres_dict
  
 @staticmethod
 defmap_fields_list_schema(fields, list_schema):
  """根據(jù)字段的模式,返回模式和數(shù)據(jù)值的對應(yīng)值;例如 fields為['a','b','c'],schema為{'name', 'age'},那么就返回{'name':'a','age':'b'}
  @param fields: 包含有數(shù)據(jù)的數(shù)組,一般是通過對一個Line String通過按照\t分割得到
  @param list_schema: 列名稱的列表list
  @return: 詞典,key是字段名稱,value是字段
  """
  dict_schema=FileUtil.transform_list_to_dict(list_schema)
  returnFileUtil.map_fields_dict_schema(fields, dict_schema)
  
@staticmethod
defmap_fields_dict_schema(fields, dict_schema):
 """根據(jù)字段的模式,返回模式和數(shù)據(jù)值的對應(yīng)值;例如 fields為['a','b','c'],schema為{'name':0, 'age':1},那么就返回{'name':'a','age':'b'}
 @param fields: 包含有數(shù)據(jù)的數(shù)組,一般是通過對一個Line String通過按照\t分割得到
 @param dict_schema: 一個詞典,key是字段名稱,value是字段的位置;
 @return: 詞典,key是字段名稱,value是字段
 """
 pdict={}
 forfstr, findexindict_schema.iteritems():
  pdict[fstr]=str(fields[int(findex)])
 returnpdict

總結(jié)

以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家學(xué)習(xí)或者使用python能有一定的幫助



數(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(), // 加隨機數(shù)防止緩存 type: "get", dataType: "json", success: function (data) { $('#text').hide(); $('#wait').show(); // 調(diào)用 initGeetest 進行初始化 // 參數(shù)1:配置參數(shù) // 參數(shù)2:回調(diào),回調(diào)的第一個參數(shù)驗證碼對象,之后可以使用它調(diào)用相應(yīng)的接口 initGeetest({ // 以下 4 個配置參數(shù)為必須,不能缺少 gt: data.gt, challenge: data.challenge, offline: !data.success, // 表示用戶后臺檢測極驗服務(wù)器是否宕機 new_captcha: data.new_captcha, // 用于宕機時表示是新驗證碼的宕機 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){ //倒計時完成 $(".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); }