python3-cookbook笔记:第六章 数据编码和处理
python3-cookbook中每个小节以问题、解决方案和讨论三个部分探讨了Python3在某类问题中的最优解决方式,或者说是探讨Python3本身的数据结构、函数、类等特性在某类问题上如何更好地使用。这本书对于加深Python3的理解和提升Python编程能力的都有显著帮助,特别是对怎么提高Python程序的性能会有很好的帮助,如果有时间的话强烈建议看一下。 ? ?6.1 读写CSV数据 对于CSV文件,如果不是需要特殊处理,为了尽可能少地出意外,那么总是应该选择CSV模块来读写CSV文件。下面只列几个简单读写CSV文件的示例: CSV文件stocks.csv,内容如下: Symbol,Price,Date,Time,Change,Volume "AA",39.48,"6/11/2007","9:36am",-0.18,181800 "AIG",71.38,-0.15,195500 "AXP",62.58,-0.46,935000 "BA",98.31,+0.12,104800 "C",53.08,-0.25,360900 "CAT",78.29,-0.23,225400 import csv # 以列表形式读取数据 csv headers = [Symbol',PriceDateTimeChangeVolume] rows = [(AA6/11/20079:36am),(AIGAXP# 以列表形式写入数据 with open(w csv.writer(f) 写入单行数据 f_csv.writerow(headers) 写入多行数据 f_csv.writerows(rows) headers = [] rows = [{':':39.48,1)">,':-0.18,1)">':181800},{': 71.38,1)">':-0.15,1)">': 195500': 62.58,1)">':-0.46,1)">': 935000 以字典形式写入数据 with open( csv.DictWriter(f,headers) f_csv.writeheader() f_csv.writerows(rows) ? ? 6.3 解析简单的XML数据 就如此小节的标题所写,这里只讲了简单的XML解析,如果是较小且不复杂的XML文件,可以使用内置的xml.etree.ElementTree,如果是复杂的XML文档,可以使用三方库lxml,功能更加强大且速度更快。对于以下示例代码,可以直接替换为from lxml.etree import parse。 from urllib.request urlopen from xml.etree.ElementTree parse 下载XML文件并解析 u = urlopen(http://planet.python.org/rss20.xml) doc = parse(u) 查找节点channel下的title节点 e = doc.find(channel/title) 打印节点名称:title (e.tag) 打印节点文本:Planet Python (e.text) 打印节点的某个属性值,因为这个节点没有其他属性,所以获取xxx的结果就是None print(e.get(xxx)) 遍历channel下的item节点 for item in doc.iterfind(channel/item): 在item节点中查找对应子节点的文本 title = item.findtext(title) date = item.findtext(pubDate) link = item.findtext(link) (title) (date) (link) print() title Planet Python None Codementor: Automating Everything With Python: Reading Time: 3 Mins Sat,22 Feb 2020 09:01:58 +0000 https://www.codementor.io/maxongzb/automating-everything-with-python-reading-time-3-mins-13v57qt7y6 Quansight Labs Blog: My Unexpected Dive into Open-Source Python Fri,21 Feb 2020 18:38:07 +0000 https://labs.quansight.org/blog/2020/02/my-unexpected-dive-into-open-source-python/ ... ? ? 6.4 增量式解析大型XML文件 如果需要解析的XML文件太大,那么可以考虑使用from xml.etree.ElementTree import iterparse进行增量式解析,需要说明的是,以下示例的两个版本中,将整个XML文档加载到内存中的做法性能要优于增量式解析,但是在内存的占用消耗上却是要远远大于增量式解析了。 需要解析的XML文件potholes.xml部分内容如下,现在需要对row节点中zip节点的内容进行统计: <response> row> row ...> creation_date>2012-11-18T00:00:00</status>Completedcompletion_dateservice_request_number>12-01906549type_of_service_request>Pot Hole in Streetcurrent_activity>Final Outcomemost_recent_action>CDOT Street Cut ... Outcomestreet_address>4714 S TALMAN AVEzip>60632x_coordinate>1159494.68618856y_coordinate>1873313.83503384ward>14police_district>9community_area>58latitude>41.808090232127896longitude>-87.69053684711305location ="41.808090232127896" longitude="-87.69053684711305" /> >12-01906695>3510 W NORTH AVE>60647>1152732.14127696>1910409.38979075>26>23>41.91002084292946>-87.71435952353961="41.91002084292946"="-87.71435952353961" > > 全部加载到内存中解析: parse from collections Counter potholes_by_zip = Counter() doc = parse(potholes.xmlfor pothole row/row): potholes_by_zip[pothole.findtext(zip')] += 1 for zipcode,num potholes_by_zip.most_common(): print(zipcode,num) 增量式解析: iterparse Counter def parse_and_remove(filename,path): path_parts = path.split(/) start事件:某个节点被创建时产生 end事件:某个节点被创建完成时产生 doc = iterparse(filename,(startend)) 跳过根节点 next(doc) tag_stack = [] elem_stack = [] for event,elem doc: if event == : tag_stack.append(elem.tag) elem_stack.append(elem) elif event == : if tag_stack == path_parts: yield elem 此处是减少内存消耗的核心语句:把yield产生的元素从它的父节点中删除掉 elem_stack[-2].remove(elem) try: tag_stack.pop() elem_stack.pop() except IndexError: pass potholes_by_zip = Counter() data = parse_and_remove( data: potholes_by_zip[pothole.findtext(6.5 将字典转换为XML
预先准备好的的文件pred.xml: <?xml version="1.0"?> stopid>14791nm>Clark & Balmoralsrirt>22d>North Boundddcrprept>5 MINfd>Howardv>1378rn>15 MIN>1867> >>> parse,Element >>> doc = parse(pred.xml) >>> root = doc.getroot() >>> root <Element stop' at 0x100770cb0> >>> root.remove(root.find(sri)) >>> root.remove(root.find(cr)) >>> root.getchildren().index(root.find(nm)) 1 >>> e = Element(spam) >>> e.text = This is a test' >>> root.insert(2newpred.xmlTrue) >>> ? (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |