侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

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

Python  /  管理员 发布于 7年前   141

前言

Python用于处理文本数据绝对是个利器,极为简单的读取、分割、过滤、转换支持,使得开发者不需要考虑繁杂的流文件处理过程(相对于JAVA来说的,嘻嘻)。博主自己工作中,一些复杂的文本数据处理计算,包括在HADOOP上编写Streaming程序,均是用Python完成。

而在文本处理的过程中,将文件加载内存中是第一步,这就涉及到怎样将文件中的某一列映射到具体的变量的过程,最最愚笨的方法,就是按照字段的下标进行引用,比如这样子:

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

如果按照这种方式读取,一旦文件有顺序、增减列的变动,代码的维护是个噩梦,这种代码一定要杜绝。

本文推荐两种优雅的方式来读取数据,都是先配置字段模式,然后按照模式读取,而模式则有字典模式和列表模式两种形式;

读取文件,按照分隔符分割成字段数据列表

首先读取文件,按照分隔符分割每一行的数据,返回字段列表,以便后续处理。

代码如下:

def read_file_data(filepath): '''根据路径按行读取文件, 参数filepath:文件的绝对路径 @param filepath: 读取文件的路径 @return: 按\t分割后的每行的数据列表 ''' 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  # 抛出当前行的分割列表  yield fields fin.close()

使用yield关键字,每次抛出单个行的分割数据,这样在调度程序中可以用for fields in read_file_data(fpath)的方式读取每一行。

映射到模型之方法1:使用配置好的字典模式,装配读取的数据列表

这种方法配置一个{“字段名”: 字段位置}的字典作为数据模式,然后按照该模式装配读取的列表数据,最后实现用字典的方式访问数据。

所使用的函数:

@staticmethoddef map_fields_dict_schema(fields, dict_schema): """根据字段的模式,返回模式和数据值的对应值;例如 fields为['a','b','c'],schema为{'name':0, 'age':1},那么就返回{'name':'a','age':'b'} @param fields: 包含有数据的数组,一般是通过对一个Line String通过按照\t分割得到 @param dict_schema: 一个词典,key是字段名称,value是字段的位置; @return: 词典,key是字段名称,value是字段值 """ pdict = {} for fstr, findex in dict_schema.iteritems():  pdict[fstr] = str(fields[int(findex)]) return pdict

有了该方法和之前的方法,可以用以下的方式读取数据:

# coding:utf8"""@author: www.crazyant.net测试使用字典模式加载数据列表优点:对于多列文件,只通过配置需要读取的字段,就能读取对应列的数据缺点:如果字段较多,每个字段的位置配置,较为麻烦"""import file_utilimport pprint # 配置好的要读取的字典模式,可以只配置自己关心的列的位置dict_schema = {"userid":0, "username":1, "usertype":2}for fields in file_util.FileUtil.read_file_data("userfile.txt"): # 将字段列表,按照字典模式进行映射 dict_fields = file_util.FileUtil.map_fields_dict_schema(fields, dict_schema) pprint.pprint(dict_fields)

输出结果:

{'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:使用配置好的列表模式,装配读取的数据列表

如果需要读取文件所有列,或者前面的一些列,那么配置字典模式优点复杂,因为需要给每个字段配置索引位置,并且这些位置是从0开始完后数的,属于低级劳动,需要消灭。

列表模式应命运而生,先将配置好的列表模式转换成字典模式,然后按字典加载就可以实现。

转换模式,以及用按列表模式读取的代码:

@staticmethoddef transform_list_to_dict(para_list): """把['a', 'b']转换成{'a':0, 'b':1}的形式 @param para_list: 列表,里面是每个列对应的字段名 @return: 字典,里面是字段名和位置的映射 """ res_dict = {} idx = 0 while idx < len(para_list):  res_dict[str(para_list[idx]).strip()] = idx  idx += 1 return res_dict @staticmethoddef map_fields_list_schema(fields, list_schema): """根据字段的模式,返回模式和数据值的对应值;例如 fields为['a','b','c'],schema为{'name', 'age'},那么就返回{'name':'a','age':'b'} @param fields: 包含有数据的数组,一般是通过对一个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)

使用的时候,可以用列表的形式配置模式,不需要配置索引更加简洁:

# coding:utf8"""@author: www.crazyant.net测试使用列表模式加载数据列表优点:如果读取所有列,用列表模式只需要按顺序写出各个列的字段名就可以缺点:不能够只读取关心的字段,需要全部读取"""import file_utilimport pprint # 配置好的要读取的列表模式,只能配置前面的列,或者所有咧list_schema = ["userid", "username", "usertype"]for fields in file_util.FileUtil.read_file_data("userfile.txt"): # 将字段列表,按照字典模式进行映射 dict_fields = file_util.FileUtil.map_fields_list_schema(fields, list_schema) pprint.pprint(dict_fields) 

运行结果和字典模式的完全一样。

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):  '''根据路径按行读取文件, 参数filepath:文件的绝对路径  @param filepath: 读取文件的路径  @return: 按\t分割后的每行的数据列表  '''  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   # 抛出当前行的分割列表   yield fields  fin.close()  @staticmethod def transform_list_to_dict(para_list):  """把['a', 'b']转换成{'a':0, 'b':1}的形式  @param para_list: 列表,里面是每个列对应的字段名  @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):  """根据字段的模式,返回模式和数据值的对应值;例如 fields为['a','b','c'],schema为{'name', 'age'},那么就返回{'name':'a','age':'b'}  @param fields: 包含有数据的数组,一般是通过对一个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) @staticmethoddef map_fields_dict_schema(fields, dict_schema): """根据字段的模式,返回模式和数据值的对应值;例如 fields为['a','b','c'],schema为{'name':0, 'age':1},那么就返回{'name':'a','age':'b'} @param fields: 包含有数据的数组,一般是通过对一个Line String通过按照\t分割得到 @param dict_schema: 一个词典,key是字段名称,value是字段的位置; @return: 词典,key是字段名称,value是字段值 """ pdict = {} for fstr, findex in dict_schema.iteritems():  pdict[fstr] = str(fields[int(findex)]) return pdict

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家学习或者使用python能有一定的帮助,如果有疑问大家可以留言交流。


  • 上一条:
    python中执行shell的两种方法总结
    下一条:
    python导入时小括号大作用
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在python语言中Flask框架的学习及简单功能示例(0个评论)
    • 在Python语言中实现GUI全屏倒计时代码示例(0个评论)
    • Python + zipfile库实现zip文件解压自动化脚本示例(0个评论)
    • python爬虫BeautifulSoup快速抓取网站图片(1个评论)
    • vscode 配置 python3开发环境的方法(0个评论)
    • 近期文章
    • 智能合约Solidity学习CryptoZombie第四课:僵尸作战系统(0个评论)
    • 智能合约Solidity学习CryptoZombie第三课:组建僵尸军队(高级Solidity理论)(0个评论)
    • 智能合约Solidity学习CryptoZombie第二课:让你的僵尸猎食(0个评论)
    • 智能合约Solidity学习CryptoZombie第一课:生成一只你的僵尸(0个评论)
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2018-04
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2022-01
    • 2023-07
    • 2023-10
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客