Python用list或dict字段模式讀取文件的方法
前言
Python用于處理文本數(shù)據(jù)絕對(duì)是個(gè)利器,極為簡(jiǎn)單的讀取、分割、過濾、轉(zhuǎn)換支持,使得開發(fā)者不需要考慮繁雜的流文件處理過程(相對(duì)于JAVA來說的,嘻嘻)。博主自己工作中,一些復(fù)雜的文本數(shù)據(jù)處理計(jì)算,包括在HADOOP上編寫Streaming程序,均是用Python完成。
而在文本處理的過程中,將文件加載內(nèi)存中是第一步,這就涉及到怎樣將文件中的某一列映射到具體的變量的過程,最最愚笨的方法,就是按照字段的下標(biāo)進(jìn)行引用,比如這樣子:
# fields是讀取了一行,并且按照分隔符分割之后的列表 user_id = fields[0] user_name = fields[1] user_type = fields[2]
如果按照這種方式讀取,一旦文件有順序、增減列的變動(dòng),代碼的維護(hù)是個(gè)噩夢(mèng),這種代碼一定要杜絕。
本文推薦兩種優(yōu)雅的方式來讀取數(shù)據(jù),都是先配置字段模式,然后按照模式讀取,而模式則有字典模式和列表模式兩種形式;
讀取文件,按照分隔符分割成字段數(shù)據(jù)列表
首先讀取文件,按照分隔符分割每一行的數(shù)據(jù),返回字段列表,以便后續(xù)處理。
代碼如下:
def read_file_data(filepath):
'''根據(jù)路徑按行讀取文件, 參數(shù)filepath:文件的絕對(duì)路徑
@param filepath: 讀取文件的路徑
@return: 按\t分割后的每行的數(shù)據(jù)列表
'''
fin = open(filepath, 'r')
for line in fin:
try:
line = line[:-1]
if not line: continue
except:
continue
try:
fields = line.split("\t")
except:
continue
# 拋出當(dāng)前行的分割列表
yield fields
fin.close()
使用yield關(guān)鍵字,每次拋出單個(gè)行的分割數(shù)據(jù),這樣在調(diào)度程序中可以用for fields in read_file_data(fpath)的方式讀取每一行。
映射到模型之方法1:使用配置好的字典模式,裝配讀取的數(shù)據(jù)列表
這種方法配置一個(gè){“字段名”: 字段位置}的字典作為數(shù)據(jù)模式,然后按照該模式裝配讀取的列表數(shù)據(jù),最后實(shí)現(xiàn)用字典的方式訪問數(shù)據(jù)。
所使用的函數(shù):
@staticmethod
def map_fields_dict_schema(fields, dict_schema):
"""根據(jù)字段的模式,返回模式和數(shù)據(jù)值的對(duì)應(yīng)值;例如 fields為['a','b','c'],schema為{'name':0, 'age':1},那么就返回{'name':'a','age':'b'}
@param fields: 包含有數(shù)據(jù)的數(shù)組,一般是通過對(duì)一個(gè)Line String通過按照\t分割得到
@param dict_schema: 一個(gè)詞典,key是字段名稱,value是字段的位置;
@return: 詞典,key是字段名稱,value是字段值
"""
pdict = {}
for fstr, findex in dict_schema.iteritems():
pdict[fstr] = str(fields[int(findex)])
return pdict
有了該方法和之前的方法,可以用以下的方式讀取數(shù)據(jù):
# coding:utf8
"""
@author: www.crazyant.net
測(cè)試使用字典模式加載數(shù)據(jù)列表
優(yōu)點(diǎn):對(duì)于多列文件,只通過配置需要讀取的字段,就能讀取對(duì)應(yīng)列的數(shù)據(jù)
缺點(diǎn):如果字段較多,每個(gè)字段的位置配置,較為麻煩
"""
import file_util
import pprint
# 配置好的要讀取的字典模式,可以只配置自己關(guān)心的列的位置
dict_schema = {"userid":0, "username":1, "usertype":2}
for fields in file_util.FileUtil.read_file_data("userfile.txt"):
# 將字段列表,按照字典模式進(jìn)行映射
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)點(diǎn)復(fù)雜,因?yàn)樾枰o每個(gè)字段配置索引位置,并且這些位置是從0開始完后數(shù)的,屬于低級(jí)勞動(dòng),需要消滅。
列表模式應(yīng)命運(yùn)而生,先將配置好的列表模式轉(zhuǎn)換成字典模式,然后按字典加載就可以實(shí)現(xiàn)。
轉(zhuǎn)換模式,以及用按列表模式讀取的代碼:
@staticmethod
def transform_list_to_dict(para_list):
"""把['a', 'b']轉(zhuǎn)換成{'a':0, 'b':1}的形式
@param para_list: 列表,里面是每個(gè)列對(duì)應(yīng)的字段名
@return: 字典,里面是字段名和位置的映射
"""
res_dict = {}
idx = 0
while idx < len(para_list):
res_dict[str(para_list[idx]).strip()] = idx
idx += 1
return res_dict
@staticmethod
def map_fields_list_schema(fields, list_schema):
"""根據(jù)字段的模式,返回模式和數(shù)據(jù)值的對(duì)應(yīng)值;例如 fields為['a','b','c'],schema為{'name', 'age'},那么就返回{'name':'a','age':'b'}
@param fields: 包含有數(shù)據(jù)的數(shù)組,一般是通過對(duì)一個(gè)Line String通過按照\t分割得到
@param list_schema: 列名稱的列表list
@return: 詞典,key是字段名稱,value是字段值
"""
dict_schema = FileUtil.transform_list_to_dict(list_schema)
return FileUtil.map_fields_dict_schema(fields, dict_schema)
使用的時(shí)候,可以用列表的形式配置模式,不需要配置索引更加簡(jiǎn)潔:
# coding:utf8
"""
@author: www.crazyant.net
測(cè)試使用列表模式加載數(shù)據(jù)列表
優(yōu)點(diǎn):如果讀取所有列,用列表模式只需要按順序?qū)懗龈鱾€(gè)列的字段名就可以
缺點(diǎn):不能夠只讀取關(guān)心的字段,需要全部讀取
"""
import file_util
import pprint
# 配置好的要讀取的列表模式,只能配置前面的列,或者所有咧
list_schema = ["userid", "username", "usertype"]
for fields in file_util.FileUtil.read_file_data("userfile.txt"):
# 將字段列表,按照字典模式進(jìn)行映射
dict_fields = file_util.FileUtil.map_fields_list_schema(fields, list_schema)
pprint.pprint(dict_fields)
運(yùn)行結(jié)果和字典模式的完全一樣。
file_util.py全部代碼
以下是file_util.py中的全部代碼,可以放在自己的公用類庫中使用
# -*- encoding:utf8 -*-
'''
@author: www.crazyant.net
@version: 2014-12-5
'''
class FileUtil(object):
'''文件、路徑常用操作方法
'''
@staticmethod
def read_file_data(filepath):
'''根據(jù)路徑按行讀取文件, 參數(shù)filepath:文件的絕對(duì)路徑
@param filepath: 讀取文件的路徑
@return: 按\t分割后的每行的數(shù)據(jù)列表
'''
fin = open(filepath, 'r')
for line in fin:
try:
line = line[:-1]
if not line: continue
except:
continue
try:
fields = line.split("\t")
except:
continue
# 拋出當(dāng)前行的分割列表
yield fields
fin.close()
@staticmethod
def transform_list_to_dict(para_list):
"""把['a', 'b']轉(zhuǎn)換成{'a':0, 'b':1}的形式
@param para_list: 列表,里面是每個(gè)列對(duì)應(yīng)的字段名
@return: 字典,里面是字段名和位置的映射
"""
res_dict = {}
idx = 0
while idx < len(para_list):
res_dict[str(para_list[idx]).strip()] = idx
idx += 1
return res_dict
@staticmethod
def map_fields_list_schema(fields, list_schema):
"""根據(jù)字段的模式,返回模式和數(shù)據(jù)值的對(duì)應(yīng)值;例如 fields為['a','b','c'],schema為{'name', 'age'},那么就返回{'name':'a','age':'b'}
@param fields: 包含有數(shù)據(jù)的數(shù)組,一般是通過對(duì)一個(gè)Line String通過按照\t分割得到
@param list_schema: 列名稱的列表list
@return: 詞典,key是字段名稱,value是字段值
"""
dict_schema = FileUtil.transform_list_to_dict(list_schema)
return FileUtil.map_fields_dict_schema(fields, dict_schema)
@staticmethod
def map_fields_dict_schema(fields, dict_schema):
"""根據(jù)字段的模式,返回模式和數(shù)據(jù)值的對(duì)應(yīng)值;例如 fields為['a','b','c'],schema為{'name':0, 'age':1},那么就返回{'name':'a','age':'b'}
@param fields: 包含有數(shù)據(jù)的數(shù)組,一般是通過對(duì)一個(gè)Line String通過按照\t分割得到
@param dict_schema: 一個(gè)詞典,key是字段名稱,value是字段的位置;
@return: 詞典,key是字段名稱,value是字段值
"""
pdict = {}
for fstr, findex in dict_schema.iteritems():
pdict[fstr] = str(fields[int(findex)])
return pdict
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對(duì)大家學(xué)習(xí)或者使用python能有一定的幫助,如果有疑問大家可以留言交流。
相關(guān)文章
Python 如何利用pandas 和 matplotlib繪制柱狀圖
Python 中的 pandas 和 matplotlib 庫提供了豐富的功能,可以幫助你輕松地繪制各種類型的圖表,本文將介紹如何使用這兩個(gè)庫,繪制一個(gè)店鋪銷售數(shù)量的柱狀圖,并添加各種元素,如數(shù)據(jù)標(biāo)簽、圖例、網(wǎng)格線等,感興趣的朋友一起看看吧2023-10-10
分享8點(diǎn)超級(jí)有用的Python編程建議(推薦)
這篇文章主要介紹了分享8點(diǎn)超級(jí)有用的Python編程建議(推薦),小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2019-10-10
Python字符串和正則表達(dá)式中的反斜杠(''\'')問題詳解
在本篇文章里小編給大家整理的是關(guān)于Python字符串和正則表達(dá)式中的反斜杠('\')問題以及相關(guān)知識(shí)點(diǎn),有需要的朋友們可以學(xué)習(xí)下。2019-09-09
Python設(shè)計(jì)模式之中介模式簡(jiǎn)單示例
這篇文章主要介紹了Python設(shè)計(jì)模式之中介模式,簡(jiǎn)單介紹了中介模式的概念、功能,并結(jié)合實(shí)例形式給出了Python定義與使用中介模式的相關(guān)操作技巧,需要的朋友可以參考下2018-01-01
Python使用Matplotlib繪制甘特圖的實(shí)踐
甘特圖已經(jīng)發(fā)展成項(xiàng)目規(guī)劃和跟蹤的必備工具,本文主要介紹了Python使用Matplotlib繪制甘特圖的實(shí)踐,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-12-12
Python函數(shù)中的函數(shù)(閉包)用法實(shí)例
這篇文章主要介紹了Python函數(shù)中的函數(shù)(閉包)用法,結(jié)合實(shí)例形式分析了Python閉包的定義與使用技巧,需要的朋友可以參考下2016-03-03
Django模型修改及數(shù)據(jù)遷移實(shí)現(xiàn)解析
這篇文章主要介紹了Django模型修改及數(shù)據(jù)遷移實(shí)現(xiàn)解析,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-08-08

