分析Python中解析構(gòu)建數(shù)據(jù)知識(shí)
Python 可以通過各種庫(kù)去解析我們常見的數(shù)據(jù)。其中 csv 文件以純文本形式存儲(chǔ)表格數(shù)據(jù),以某字符作為分隔值,通常為逗號(hào);xml 可拓展標(biāo)記語言,很像超文本標(biāo)記語言 Html ,但主要對(duì)文檔和數(shù)據(jù)進(jìn)行結(jié)構(gòu)化處理,被用來傳輸數(shù)據(jù);json 作為一種輕量級(jí)數(shù)據(jù)交換格式,比 xml 更小巧但描述能力卻不差,其本質(zhì)是特定格式的字符串;Microsoft Excel 是電子表格,可進(jìn)行各種數(shù)據(jù)的處理、統(tǒng)計(jì)分析和輔助決策操作,其數(shù)據(jù)格式為 xls、xlsx。接下來主要介紹通過 Python 簡(jiǎn)單解析構(gòu)建上述數(shù)據(jù),完成數(shù)據(jù)的“珍珠翡翠白玉湯”。
Python 解析構(gòu)建 csv
通過標(biāo)準(zhǔn)庫(kù)中的 csv 模塊,使用函數(shù) reader()、writer() 完成 csv 數(shù)據(jù)基本讀寫。
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() 寫入一行或多行數(shù)據(jù)。兩者還可通過參數(shù) dialect 指定編碼方式,默認(rèn)以 excel 方式,即以逗號(hào)分隔,通過參數(shù) delimiter 指定分隔字段的單字符,默認(rèn)為逗號(hào)。
在 Python3 中,打開文件對(duì)象 csvfile ,需要通過 newline='' 指定換行處理,這樣讀取文件時(shí),新行才能被正確地解釋;而在 Python2 中,文件對(duì)象 csvfile 必須以二進(jìn)制的方式 'b' 讀寫,否則會(huì)將某些字節(jié)(0x1A)讀寫為文檔結(jié)束符(EOF),導(dǎo)致文檔讀取不全。
除此之外,還可使用 csv 模塊中的類 DictReader()、DictWriter() 進(jìn)行字典方式讀寫。
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() 返回有序字典,使得數(shù)據(jù)可通過字典的形式訪問,鍵名由參數(shù) fieldnames 指定,默認(rèn)為讀取的第一行。
DictWriter() 必須指定參數(shù) fieldnames 說明鍵名,通過 writeheader() 將鍵名寫入,通過 writerrow() 或 writerrows() 寫入一行或多行字典數(shù)據(jù)。
Python 解析構(gòu)建 xml
通過標(biāo)準(zhǔn)庫(kù)中的 xml.etree.ElementTree 模塊,使用 Element、ElementTree 完成 xml 數(shù)據(jù)的讀寫。
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 文件時(shí),通過 Element() 構(gòu)建節(jié)點(diǎn),set() 設(shè)置屬性和相應(yīng)值,append() 添加子節(jié)點(diǎn),extend() 結(jié)合循環(huán)器中的 chain() 合成列表添加一組節(jié)點(diǎn),text 屬性設(shè)置文本值,ElementTree() 傳入根節(jié)點(diǎn)構(gòu)建樹,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 文件時(shí),通過 ElementTree() 構(gòu)建空樹,parse() 讀入 xml 文件,解析映射到空樹;getroot() 獲取根節(jié)點(diǎn),通過下標(biāo)可訪問相應(yīng)的節(jié)點(diǎn);tag 獲取節(jié)點(diǎn)名,attrib 獲取節(jié)點(diǎn)屬性字典,text 獲取節(jié)點(diǎn)文本;find() 返回匹配到節(jié)點(diǎn)名的第一個(gè)節(jié)點(diǎn),findall() 返回匹配到節(jié)點(diǎn)名的所有節(jié)點(diǎn),find()、findall() 兩者都僅限當(dāng)前節(jié)點(diǎn)的一級(jí)子節(jié)點(diǎn),都支持 xpath 路徑提取節(jié)點(diǎn);iter() 創(chuàng)建樹迭代器,遍歷當(dāng)前節(jié)點(diǎn)的所有子節(jié)點(diǎn),返回匹配到節(jié)點(diǎn)名的所有節(jié)點(diǎn);remove() 移除相應(yīng)的節(jié)點(diǎn)。
除此之外,還可通過 xml.sax、xml.dom.minidom 去解析構(gòu)建 xml 數(shù)據(jù)。其中 sax 是基于事件處理的;dom 是將 xml 數(shù)據(jù)在內(nèi)存中解析成一個(gè)樹,通過對(duì)樹的操作來操作 xml;而 ElementTree 是輕量級(jí)的 dom ,具有簡(jiǎn)單而高效的API,可用性好,速度快,消耗內(nèi)存少,但生成的數(shù)據(jù)格式不美觀,需要手動(dòng)格式化。
Python 解析構(gòu)建 json
通過標(biāo)準(zhǔn)庫(kù)中的 json 模塊,使用函數(shù) dumps()、loads() 完成 json 數(shù)據(jù)基本讀寫。
>>> 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() 可通過參數(shù) ensure_ascii 指定是否使用 ascii 編碼,默認(rèn)為 True;通過參數(shù) separators=(',', ':') 指定 json 數(shù)據(jù)格式中的兩種分隔符;通過參數(shù) sort_keys 指定是否使用排序,默認(rèn)為 False。
除此之外,還可使用 json 模塊中的函數(shù) dump()、load() 進(jìn)行 json 數(shù)據(jù)讀寫。
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() 相同,但接口不同,需要與文件操作結(jié)合,多傳入一個(gè)文件對(duì)象。
Python 解析構(gòu)建 excel
通過 pip 安裝第三方庫(kù) xlwt、xlrd 模塊,完成 excel 數(shù)據(jù)的讀寫。
import xlwt
wbook = xlwt.Workbook(encoding='utf-8')
wsheet = wbook.add_sheet('sheet1')
wsheet.write(0, 0, 'Hello World')
wbook.save('exceltest.xls')
寫 excel 數(shù)據(jù)時(shí),通過 xlwt.Workbook() 指定編碼格式參數(shù) encoding 創(chuàng)建工作表,add_sheet() 添加表單,write() 在相應(yīng)的行列單元格中寫入數(shù)據(jù),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 數(shù)據(jù)時(shí),通過 xlrd.open_workbook() 打開相應(yīng)的工作表,可使用列表下標(biāo)、表索引 sheet_by_index()、表單名 sheet_by_name() 三種方式獲取表單名,nrows 獲取行數(shù),ncols 獲取列數(shù),row_values() 返回相應(yīng)行的值列表,col_values() 返回相應(yīng)列的值列表,cell_value() 返回相應(yīng)行列的單元格值。
相關(guān)文章
Python自定義命令行參數(shù)選項(xiàng)和解析器
這篇文章主要介紹了Python自定義命令行參數(shù)選項(xiàng)和解析器,本文主要使用的方法為argparse.ArgumentParser(),此模塊可以讓人輕松編寫用戶友好的命令行接口,程序定義它需要的參數(shù),需要的朋友可以參考下2023-07-07
PyQt轉(zhuǎn)換路徑中的斜杠(斜杠(/)與反斜杠(\)轉(zhuǎn)換)
本文主要介紹了PyQt轉(zhuǎn)換路徑中的斜杠(斜杠(/)與反斜杠(\)轉(zhuǎn)換),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-07-07
python創(chuàng)建ArcGIS shape文件的實(shí)現(xiàn)
今天小編就為大家分享一篇python創(chuàng)建ArcGIS shape文件的實(shí)現(xiàn),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2019-12-12
詳談pandas中agg函數(shù)和apply函數(shù)的區(qū)別
下面小編就為大家分享一篇詳談pandas中agg函數(shù)和apply函數(shù)的區(qū)別,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-04-04
Python腳本實(shí)現(xiàn)調(diào)用手機(jī)攝像頭
這篇文章主要為大家詳細(xì)介紹了Python如何通過,腳本實(shí)現(xiàn)調(diào)用手機(jī)攝像頭,這樣就能隨時(shí)隨地用電腦偷偷看看男朋友都在干啥了,感興趣的小伙伴可以了解下2025-03-03
Python3使用pywinauto如何檢測(cè)需要獲取程序元素
這篇文章主要為大家詳細(xì)介紹了Python3使用pywinauto如何檢測(cè)需要獲取程序元素,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以參考一下2025-02-02
Python2與python3中 for 循環(huán)語句基礎(chǔ)與實(shí)例分析
Python for循環(huán)可以遍歷任何序列的項(xiàng)目,如一個(gè)列表或者一個(gè)字符串,也是python中比較常用的一個(gè)函數(shù),這里通過基礎(chǔ)與實(shí)例給大家分享一下2017-11-11
Python環(huán)境使用OpenCV檢測(cè)人臉實(shí)現(xiàn)教程
這篇文章主要介紹了Python環(huán)境使用OpenCV檢測(cè)人臉實(shí)現(xiàn)教程,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-10-10
python selenium 執(zhí)行完畢關(guān)閉chromedriver進(jìn)程示例
今天小編就為大家分享一篇python selenium 執(zhí)行完畢關(guān)閉chromedriver進(jìn)程示例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2019-11-11

