没有合适的资源?快使用搜索试试~ 我知道了~
资源推荐
资源详情
资源评论
分析分析Python中解析构建数据知识中解析构建数据知识
本篇文章给大家讲述一下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()
资源评论
weixin_38674223
- 粉丝: 3
- 资源: 951
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功