
分析Python中解析構(gòu)建數(shù)據(jù)知識(shí)
Python 可以通過(guò)各種庫(kù)去解析我們常見(jiàn)的數(shù)據(jù)。其中 csv 文件以純文本形式存儲(chǔ)表格數(shù)據(jù),以某字符作為分隔值,通常為逗號(hào);xml 可拓展標(biāo)記語(yǔ)言,很像超文本標(biāo)記語(yǔ)言 Html ,但主要對(duì)文檔和數(shù)據(jù)進(jìn)行結(jié)構(gòu)化處理,被用來(lái)傳輸數(shù)據(jù);json 作為一種輕量級(jí)數(shù)據(jù)交換格式,比 xml 更小巧但描述能力卻不差,其本質(zhì)是特定格式的字符串;Microsoft Excel 是電子表格,可進(jìn)行各種數(shù)據(jù)的處理、統(tǒng)計(jì)分析和輔助決策操作,其數(shù)據(jù)格式為 xls、xlsx。接下來(lái)主要介紹通過(guò) Python 簡(jiǎn)單解析構(gòu)建上述數(shù)據(jù),完成數(shù)據(jù)的“珍珠翡翠白玉湯”。
Python 解析構(gòu)建 csv
通過(guò)標(biāo)準(zhǔn)庫(kù)中的 csv 模塊,使用函數(shù) reader()、writer() 完成 csv 數(shù)據(jù)基本讀寫(xiě)。
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() 通過(guò) writerrow() 或 writerrows() 寫(xiě)入一行或多行數(shù)據(jù)。兩者還可通過(guò)參數(shù) dialect 指定編碼方式,默認(rèn)以 excel 方式,即以逗號(hào)分隔,通過(guò)參數(shù) delimiter 指定分隔字段的單字符,默認(rèn)為逗號(hào)。
在 Python3 中,打開(kāi)文件對(duì)象 csvfile ,需要通過(guò) newline='' 指定換行處理,這樣讀取文件時(shí),新行才能被正確地解釋;而在 Python2 中,文件對(duì)象 csvfile 必須以二進(jìn)制的方式 'b' 讀寫(xiě),否則會(huì)將某些字節(jié)(0x1A)讀寫(xiě)為文檔結(jié)束符(EOF),導(dǎo)致文檔讀取不全。
除此之外,還可使用 csv 模塊中的類 DictReader()、DictWriter() 進(jìn)行字典方式讀寫(xiě)。
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ù)可通過(guò)字典的形式訪問(wèn),鍵名由參數(shù) fieldnames 指定,默認(rèn)為讀取的第一行。
DictWriter() 必須指定參數(shù) fieldnames 說(shuō)明鍵名,通過(guò) writeheader() 將鍵名寫(xiě)入,通過(guò) writerrow() 或 writerrows() 寫(xiě)入一行或多行字典數(shù)據(jù)。
Python 解析構(gòu)建 xml
通過(guò)標(biāo)準(zhǔn)庫(kù)中的 xml.etree.ElementTree 模塊,使用 Element、ElementTree 完成 xml 數(shù)據(jù)的讀寫(xiě)。
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')
寫(xiě) xml 文件時(shí),通過(guò) 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)建樹(shù),write() 寫(xiě)入 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í),通過(guò) ElementTree() 構(gòu)建空樹(shù),parse() 讀入 xml 文件,解析映射到空樹(shù);getroot() 獲取根節(jié)點(diǎn),通過(guò)下標(biāo)可訪問(wèn)相應(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)建樹(shù)迭代器,遍歷當(dāng)前節(jié)點(diǎn)的所有子節(jié)點(diǎn),返回匹配到節(jié)點(diǎn)名的所有節(jié)點(diǎn);remove() 移除相應(yīng)的節(jié)點(diǎn)。
除此之外,還可通過(guò) xml.sax、xml.dom.minidom 去解析構(gòu)建 xml 數(shù)據(jù)。其中 sax 是基于事件處理的;dom 是將 xml 數(shù)據(jù)在內(nèi)存中解析成一個(gè)樹(shù),通過(guò)對(duì)樹(shù)的操作來(lái)操作 xml;而 ElementTree 是輕量級(jí)的 dom ,具有簡(jiǎn)單而高效的API,可用性好,速度快,消耗內(nèi)存少,但生成的數(shù)據(jù)格式不美觀,需要手動(dòng)格式化。
Python 解析構(gòu)建 json
通過(guò)標(biāo)準(zhǔn)庫(kù)中的 json 模塊,使用函數(shù) dumps()、loads() 完成 json 數(shù)據(jù)基本讀寫(xiě)。
>>> 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() 可通過(guò)參數(shù) ensure_ascii 指定是否使用 ascii 編碼,默認(rèn)為 True;通過(guò)參數(shù) separators=(',', ':') 指定 json 數(shù)據(jù)格式中的兩種分隔符;通過(guò)參數(shù) sort_keys 指定是否使用排序,默認(rèn)為 False。
除此之外,還可使用 json 模塊中的函數(shù) dump()、load() 進(jìn)行 json 數(shù)據(jù)讀寫(xiě)。
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
通過(guò) pip 安裝第三方庫(kù) xlwt、xlrd 模塊,完成 excel 數(shù)據(jù)的讀寫(xiě)。
import xlwt
wbook = xlwt.Workbook(encoding='utf-8')
wsheet = wbook.add_sheet('sheet1')
wsheet.write(0, 0, 'Hello World')
wbook.save('exceltest.xls')
寫(xiě) excel 數(shù)據(jù)時(shí),通過(guò) xlwt.Workbook() 指定編碼格式參數(shù) encoding 創(chuàng)建工作表,add_sheet() 添加表單,write() 在相應(yīng)的行列單元格中寫(xiě)入數(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í),通過(guò) xlrd.open_workbook() 打開(kāi)相應(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)行列的單元格值。
數(shù)據(jù)分析咨詢請(qǐng)掃描二維碼
若不方便掃碼,搜微信號(hào):CDAshujufenxi
LSTM 模型輸入長(zhǎng)度選擇技巧:提升序列建模效能的關(guān)鍵? 在循環(huán)神經(jīng)網(wǎng)絡(luò)(RNN)家族中,長(zhǎng)短期記憶網(wǎng)絡(luò)(LSTM)憑借其解決長(zhǎng)序列 ...
2025-07-11CDA 數(shù)據(jù)分析師報(bào)考條件詳解與準(zhǔn)備指南? ? 在數(shù)據(jù)驅(qū)動(dòng)決策的時(shí)代浪潮下,CDA 數(shù)據(jù)分析師認(rèn)證愈發(fā)受到矚目,成為眾多有志投身數(shù) ...
2025-07-11數(shù)據(jù)透視表中兩列相乘合計(jì)的實(shí)用指南? 在數(shù)據(jù)分析的日常工作中,數(shù)據(jù)透視表憑借其強(qiáng)大的數(shù)據(jù)匯總和分析功能,成為了 Excel 用戶 ...
2025-07-11尊敬的考生: 您好! 我們誠(chéng)摯通知您,CDA Level I和 Level II考試大綱將于 2025年7月25日 實(shí)施重大更新。 此次更新旨在確保認(rèn) ...
2025-07-10BI 大數(shù)據(jù)分析師:連接數(shù)據(jù)與業(yè)務(wù)的價(jià)值轉(zhuǎn)化者? ? 在大數(shù)據(jù)與商業(yè)智能(Business Intelligence,簡(jiǎn)稱 BI)深度融合的時(shí)代,BI ...
2025-07-10SQL 在預(yù)測(cè)分析中的應(yīng)用:從數(shù)據(jù)查詢到趨勢(shì)預(yù)判? ? 在數(shù)據(jù)驅(qū)動(dòng)決策的時(shí)代,預(yù)測(cè)分析作為挖掘數(shù)據(jù)潛在價(jià)值的核心手段,正被廣泛 ...
2025-07-10數(shù)據(jù)查詢結(jié)束后:分析師的收尾工作與價(jià)值深化? ? 在數(shù)據(jù)分析的全流程中,“query end”(查詢結(jié)束)并非工作的終點(diǎn),而是將數(shù) ...
2025-07-10CDA 數(shù)據(jù)分析師考試:從報(bào)考到取證的全攻略? 在數(shù)字經(jīng)濟(jì)蓬勃發(fā)展的今天,數(shù)據(jù)分析師已成為各行業(yè)爭(zhēng)搶的核心人才,而 CDA(Certi ...
2025-07-09【CDA干貨】單樣本趨勢(shì)性檢驗(yàn):捕捉數(shù)據(jù)背后的時(shí)間軌跡? 在數(shù)據(jù)分析的版圖中,單樣本趨勢(shì)性檢驗(yàn)如同一位耐心的偵探,專注于從單 ...
2025-07-09year_month數(shù)據(jù)類型:時(shí)間維度的精準(zhǔn)切片? ? 在數(shù)據(jù)的世界里,時(shí)間是最不可或缺的維度之一,而year_month數(shù)據(jù)類型就像一把精準(zhǔn) ...
2025-07-09CDA 備考干貨:Python 在數(shù)據(jù)分析中的核心應(yīng)用與實(shí)戰(zhàn)技巧? ? 在 CDA 數(shù)據(jù)分析師認(rèn)證考試中,Python 作為數(shù)據(jù)處理與分析的核心 ...
2025-07-08SPSS 中的 Mann-Kendall 檢驗(yàn):數(shù)據(jù)趨勢(shì)與突變分析的有力工具? ? ? 在數(shù)據(jù)分析的廣袤領(lǐng)域中,準(zhǔn)確捕捉數(shù)據(jù)的趨勢(shì)變化以及識(shí)別 ...
2025-07-08備戰(zhàn) CDA 數(shù)據(jù)分析師考試:需要多久?如何規(guī)劃? CDA(Certified Data Analyst)數(shù)據(jù)分析師認(rèn)證作為國(guó)內(nèi)權(quán)威的數(shù)據(jù)分析能力認(rèn)證 ...
2025-07-08LSTM 輸出不確定的成因、影響與應(yīng)對(duì)策略? 長(zhǎng)短期記憶網(wǎng)絡(luò)(LSTM)作為循環(huán)神經(jīng)網(wǎng)絡(luò)(RNN)的一種變體,憑借獨(dú)特的門(mén)控機(jī)制,在 ...
2025-07-07統(tǒng)計(jì)學(xué)方法在市場(chǎng)調(diào)研數(shù)據(jù)中的深度應(yīng)用? 市場(chǎng)調(diào)研是企業(yè)洞察市場(chǎng)動(dòng)態(tài)、了解消費(fèi)者需求的重要途徑,而統(tǒng)計(jì)學(xué)方法則是市場(chǎng)調(diào)研數(shù) ...
2025-07-07CDA數(shù)據(jù)分析師證書(shū)考試全攻略? 在數(shù)字化浪潮席卷全球的當(dāng)下,數(shù)據(jù)已成為企業(yè)決策、行業(yè)發(fā)展的核心驅(qū)動(dòng)力,數(shù)據(jù)分析師也因此成為 ...
2025-07-07剖析 CDA 數(shù)據(jù)分析師考試題型:解鎖高效備考與答題策略? CDA(Certified Data Analyst)數(shù)據(jù)分析師考試作為衡量數(shù)據(jù)專業(yè)能力的 ...
2025-07-04SQL Server 字符串截取轉(zhuǎn)日期:解鎖數(shù)據(jù)處理的關(guān)鍵技能? 在數(shù)據(jù)處理與分析工作中,數(shù)據(jù)格式的規(guī)范性是保證后續(xù)分析準(zhǔn)確性的基礎(chǔ) ...
2025-07-04CDA 數(shù)據(jù)分析師視角:從數(shù)據(jù)迷霧中探尋商業(yè)真相? 在數(shù)字化浪潮席卷全球的今天,數(shù)據(jù)已成為企業(yè)決策的核心驅(qū)動(dòng)力,CDA(Certifie ...
2025-07-04CDA 數(shù)據(jù)分析師:開(kāi)啟數(shù)據(jù)職業(yè)發(fā)展新征程? ? 在數(shù)據(jù)成為核心生產(chǎn)要素的今天,數(shù)據(jù)分析師的職業(yè)價(jià)值愈發(fā)凸顯。CDA(Certified D ...
2025-07-03