国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

分析Python中解析構(gòu)建數(shù)據(jù)知識

2020-02-22 22:55:51
字體:
供稿:網(wǎng)友

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')            
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 密山市| 大港区| 清丰县| 泰宁县| 宁晋县| 宜君县| 高淳县| 平武县| 云和县| 沽源县| 彰武县| 黄石市| 滦平县| 成安县| 平和县| 自贡市| 阳信县| 乡城县| 佛冈县| 关岭| 喀喇| 金塔县| 城步| 桦甸市| 定襄县| 双柏县| 金坛市| 综艺| 枞阳县| 长沙市| 稻城县| 通江县| 忻城县| 亚东县| 清水河县| 樟树市| 峨山| 宁津县| 阿巴嘎旗| 伊宁市| 宁强县|