分析Python中解析构建数据知识


Posted in Python onJanuary 20, 2018

Python 可以通过各种库去解析我们常见的数据。其中 csv 文件以纯文本形式存储表格数据,以某字符作为分隔值,通常为逗号;xml 可拓展标记语言,很像超文本标记语言 Html ,但主要对文档和数据进行结构化处理,被用来传输数据;json 作为一种轻量级数据交换格式,比 xml 更小巧但描述能力却不差,其本质是特定格式的字符串;Microsoft Excel 是电子表格,可进行各种数据的处理、统计分析和辅助决策操作,其数据格式为 xls、xlsx。接下来主要介绍通过 Python 简单解析构建上述数据,完成数据的“珍珠翡翠白玉汤”。

Python 解析构建 csv

通过标准库中的 csv 模块,使用函数 reader()、writer() 完成 csv 数据基本读写。

import csv
with open('readtest.csv', newline='') as csvfile:
reader = csv.reader(csvfile)
for row in reader:
print(row)
with open('writetest.csv', 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerrow("onetest")
writer.writerows("someiterable")

其中 reader() 返回迭代器, writer() 通过 writerrow() 或 writerrows() 写入一行或多行数据。两者还可通过参数 dialect 指定编码方式,默认以 excel 方式,即以逗号分隔,通过参数 delimiter 指定分隔字段的单字符,默认为逗号。

在 Python3 中,打开文件对象 csvfile ,需要通过 newline='' 指定换行处理,这样读取文件时,新行才能被正确地解释;而在 Python2 中,文件对象 csvfile 必须以二进制的方式 'b' 读写,否则会将某些字节(0x1A)读写为文档结束符(EOF),导致文档读取不全。

除此之外,还可使用 csv 模块中的类 DictReader()、DictWriter() 进行字典方式读写。

import csv
with open('readtest.csv', newline='') as csvfile:
  reader = csv.DictReader(csvfile)
  for row in reader:
    print(row['first_test'], row['last_test'])
with open('writetest.csv', 'w', newline='') as csvfile:
  fieldnames = ['first_test', 'last_test']
  writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
  writer.writeheader()
  writer.writerow({'first_test': 'hello', 'last_test': 'wrold'})
  writer.writerow({'first_test': 'Hello', 'last_test': 'World'})
  #writer.writerows([{'first_test': 'hello', 'last_test': 'wrold'}, {'first_test': 'Hello', 'last_test': 'World'}])

其中 DictReader() 返回有序字典,使得数据可通过字典的形式访问,键名由参数 fieldnames 指定,默认为读取的第一行。

DictWriter() 必须指定参数 fieldnames 说明键名,通过 writeheader() 将键名写入,通过 writerrow() 或 writerrows() 写入一行或多行字典数据。

Python 解析构建 xml

通过标准库中的 xml.etree.ElementTree 模块,使用 Element、ElementTree 完成 xml 数据的读写。

from xml.etree.ElementTree import Element, ElementTree
root = Element('language')
root.set('name', 'python')
direction1 = Element('direction')
direction2 = Element('direction')
direction3 = Element('direction')
direction4 = Element('direction')
direction1.text = 'Web'
direction2.text = 'Spider'
direction3.text = 'BigData'
direction4.text = 'AI'
root.append(direction1)
root.append(direction2)
root.append(direction3)
root.append(direction4)
#import itertools
#root.extend(chain(direction1, direction2, direction3, direction4))
tree = ElementTree(root)
tree.write('xmltest.xml')

写 xml 文件时,通过 Element() 构建节点,set() 设置属性和相应值,append() 添加子节点,extend() 结合循环器中的 chain() 合成列表添加一组节点,text 属性设置文本值,ElementTree() 传入根节点构建树,write() 写入 xml 文件。

import xml.etree.ElementTree as ET
tree = ET.parse('xmltest.xml')
#from xml.etree.ElementTree import ElementTree
#tree = ElementTree().parse('xmltest.xml')
root = tree.getroot()
tag = root.tag
attrib = root.attrib
text = root.text
direction1 = root.find('direction')
direction2 = root[1]
directions = root.findall('.//direction')
for direction in root.findall('direction'):
  print(direction.text)
for direction in root.iter('direction'):
  print(direction.text)
root.remove(direction2)

读 xml 文件时,通过 ElementTree() 构建空树,parse() 读入 xml 文件,解析映射到空树;getroot() 获取根节点,通过下标可访问相应的节点;tag 获取节点名,attrib 获取节点属性字典,text 获取节点文本;find() 返回匹配到节点名的第一个节点,findall() 返回匹配到节点名的所有节点,find()、findall() 两者都仅限当前节点的一级子节点,都支持 xpath 路径提取节点;iter() 创建树迭代器,遍历当前节点的所有子节点,返回匹配到节点名的所有节点;remove() 移除相应的节点。

除此之外,还可通过 xml.sax、xml.dom.minidom 去解析构建 xml 数据。其中 sax 是基于事件处理的;dom 是将 xml 数据在内存中解析成一个树,通过对树的操作来操作 xml;而 ElementTree 是轻量级的 dom ,具有简单而高效的API,可用性好,速度快,消耗内存少,但生成的数据格式不美观,需要手动格式化。

Python 解析构建 json

通过标准库中的 json 模块,使用函数 dumps()、loads() 完成 json 数据基本读写。

>>> import json
>>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
'["foo", {"bar": ["baz", null, 1.0, 2]}]'
>>> json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]')
['foo', {'bar': ['baz', None, 1.0, 2]}]

json.dumps() 是将 obj 序列化为 json 格式的 str,而 json.loads() 是反向操作。其中 dumps() 可通过参数 ensure_ascii 指定是否使用 ascii 编码,默认为 True;通过参数  separators=(',', ':') 指定 json 数据格式中的两种分隔符;通过参数 sort_keys 指定是否使用排序,默认为 False。

除此之外,还可使用 json 模块中的函数 dump()、load() 进行 json 数据读写。

import json
with open('jsontest.json', 'w') as jsonfile:
json.dump(['foo', {'bar': ('baz', None, 1.0, 2)}], jsonfile)
with open('jsontest.json') as jsonfile:
json.load(jsonfile)

功能与 dumps()、loads() 相同,但接口不同,需要与文件操作结合,多传入一个文件对象。

Python 解析构建 excel

通过 pip 安装第三方库 xlwt、xlrd 模块,完成 excel 数据的读写。

import xlwt
wbook = xlwt.Workbook(encoding='utf-8')
wsheet = wbook.add_sheet('sheet1')
wsheet.write(0, 0, 'Hello World')
wbook.save('exceltest.xls')

写 excel 数据时,通过 xlwt.Workbook() 指定编码格式参数 encoding 创建工作表,add_sheet() 添加表单,write() 在相应的行列单元格中写入数据,save() 保存工作表。

import xlrd
rbook = xlrd.open_workbook('exceltest.xls')
rsheet = book.sheets()[0]
#rsheet = book.sheet_by_index(0)
#rsheet = book.sheet_by_name('sheet1')
nr = rsheet.nrows
nc = rsheet.ncols
rv = rsheet.row_values(0)
cv = rsheet.col_values(0)
cell = rsheet.cell_value(0, 0)

读 excel 数据时,通过 xlrd.open_workbook() 打开相应的工作表,可使用列表下标、表索引 sheet_by_index()、表单名 sheet_by_name() 三种方式获取表单名,nrows 获取行数,ncols 获取列数,row_values() 返回相应行的值列表,col_values() 返回相应列的值列表,cell_value() 返回相应行列的单元格值。

Python 相关文章推荐
Python输出带颜色的字符串实例
Oct 10 Python
Python实现PS滤镜碎片特效功能示例
Jan 24 Python
Python字符串格式化%s%d%f详解
Feb 02 Python
Python将图片转换为字符画的方法
Jun 16 Python
Django实现全文检索的方法(支持中文)
May 14 Python
使用Python机器学习降低静态日志噪声
Sep 29 Python
在python带权重的列表中随机取值的方法
Jan 23 Python
linux环境下Django的安装配置详解
Jul 22 Python
基于Python解密仿射密码
Oct 21 Python
Python生成个性签名图片获取GUI过程解析
Dec 16 Python
python GUI库图形界面开发之PyQt5菜单栏控件QMenuBar的详细使用方法与实例
Feb 28 Python
matplotlib画混淆矩阵与正确率曲线的实例代码
Jun 01 Python
学习Python selenium自动化网页抓取器
Jan 20 #Python
python使用pil库实现图片合成实例代码
Jan 20 #Python
python方向键控制上下左右代码
Jan 20 #Python
Python线程创建和终止实例代码
Jan 20 #Python
python+matplotlib实现动态绘制图片实例代码(交互式绘图)
Jan 20 #Python
Python实现PS滤镜的旋转模糊功能示例
Jan 20 #Python
浅谈flask中的before_request与after_request
Jan 20 #Python
You might like
Mysql数据库操作类( 1127版,提供源码下载 )
2010/12/02 PHP
PHP生成随机密码方法汇总
2015/08/27 PHP
php读取和保存base64编码的图片内容
2017/04/22 PHP
自制PHP框架之路由与控制器
2017/05/07 PHP
基于javascript bootstrap实现生日日期联动选择
2016/04/07 Javascript
详解nodeJS中读写文件方法的区别
2017/03/06 NodeJs
关于微信小程序map组件z-index的层级问题分析
2019/07/09 Javascript
vue中axios防止多次触发终止多次请求的示例代码(防抖)
2020/02/16 Javascript
在vue中axios设置timeout超时的操作
2020/09/04 Javascript
[02:39]DOTA2英雄基础教程 极限穿梭编织者
2013/12/05 DOTA
python将人民币转换大写的脚本代码
2013/02/10 Python
Python实现telnet服务器的方法
2015/07/10 Python
python获取元素在数组中索引号的方法
2015/07/15 Python
Django admin实现图书管理系统菜鸟级教程完整实例
2017/12/12 Python
Python单元测试简单示例
2018/07/03 Python
python socket 聊天室实例代码详解
2019/11/14 Python
python求解汉诺塔游戏
2020/07/09 Python
Python如何实现大型数组运算(使用NumPy)
2020/07/24 Python
HTML5 解决苹果手机不能自动播放音乐问题
2017/12/27 HTML / CSS
德国2018年度最佳在线药房:Bodfeld Apotheke
2019/11/04 全球购物
皇家阿尔伯特瓷器美国官网:Royal Albert美国
2020/02/16 全球购物
澳大利亚排名第一的露营和户外设备在线零售商:Outbax
2020/05/06 全球购物
简历中个人求职的自我评价模板
2013/11/29 职场文书
《学棋》教后反思
2014/04/14 职场文书
篮球比赛策划方案
2014/06/05 职场文书
英语专业自荐书
2014/06/13 职场文书
商业用房租赁协议书
2014/10/13 职场文书
销售经理工作失职检讨书
2014/10/24 职场文书
2014年大学教师工作总结
2014/12/02 职场文书
务工证明怎么写
2015/06/18 职场文书
工作态度怎么写
2015/06/25 职场文书
2016银行招聘自荐信
2016/01/28 职场文书
各类场合主持词开场白范文集锦
2019/08/16 职场文书
创业计划书之闲置物品置换中心
2019/12/25 职场文书
原生JS封装vue Tab切换效果
2021/04/28 Vue.js
golang特有程序结构入门教程
2021/06/02 Python