登录
首页精彩阅读分析Python中解析构建数据知识
分析Python中解析构建数据知识
2018-05-25
收藏

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

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() 返回相应行列的单元格值。

数据分析咨询请扫描二维码

客服在线
立即咨询