Python 可以通過各種庫去解析我們常見的數(shù)據(jù)。其中 csv 文件以純文本形式存儲表格數(shù)據(jù),以某字符作為分隔值,通常為逗號;xml 可拓展標記語言,很像超文本標記語言 Html ,但主要對文檔和數(shù)據(jù)進行結(jié)構(gòu)化處理,被用來傳輸數(shù)據(jù);json 作為一種輕量級數(shù)據(jù)交換格式,比 xml 更小巧但描述能力卻不差,其本質(zhì)是特定格式的字符串;Microsoft Excel 是電子表格,可進行各種數(shù)據(jù)的處理、統(tǒng)計分析和輔助決策操作,其數(shù)據(jù)格式為 xls、xlsx。接下來主要介紹通過 Python 簡單解析構(gòu)建上述數(shù)據(jù),完成數(shù)據(jù)的“珍珠翡翠白玉湯”。
Python 解析構(gòu)建 csv
通過標準庫中的 csv 模塊,使用函數(shù) reader()、writer() 完成 csv 數(shù)據(jù)基本讀寫。
import csvwith 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 指定編碼方式,默認以 excel 方式,即以逗號分隔,通過參數(shù) delimiter 指定分隔字段的單字符,默認為逗號。
在 Python3 中,打開文件對象 csvfile ,需要通過 newline='' 指定換行處理,這樣讀取文件時,新行才能被正確地解釋;而在 Python2 中,文件對象 csvfile 必須以二進制的方式 'b' 讀寫,否則會將某些字節(jié)(0x1A)讀寫為文檔結(jié)束符(EOF),導(dǎo)致文檔讀取不全。
除此之外,還可使用 csv 模塊中的類 DictReader()、DictWriter() 進行字典方式讀寫。
import csvwith 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 指定,默認為讀取的第一行。
DictWriter() 必須指定參數(shù) fieldnames 說明鍵名,通過 writeheader() 將鍵名寫入,通過 writerrow() 或 writerrows() 寫入一行或多行字典數(shù)據(jù)。
Python 解析構(gòu)建 xml
通過標準庫中的 xml.etree.ElementTree 模塊,使用 Element、ElementTree 完成 xml 數(shù)據(jù)的讀寫。
from xml.etree.ElementTree import Element, ElementTreeroot = 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')
|
新聞熱點
疑難解答