《Python Cookbook(第3版)中文版》——6.4 以增量方式解析大型XML文件

    xiaoxiao2023-12-16  150

    本节书摘来自异步社区《Python Cookbook(第3版)中文版》一书中的第6章,第6.4节,作者[美]David Beazley , Brian K.Jones,陈舸 译,更多章节内容可以访问云栖社区“异步社区”公众号查看。

    6.4 以增量方式解析大型XML文件

    6.4.1 问题

    我们需要从一个大型的XML文档中提取出数据,而且对内存的使用要尽可能少。

    6.4.2 解决方案

    任何时候,当要面对以增量方式处理数据的问题时,都应该考虑使用迭代器和生成器。下面是一个简单的函数,可用来以增量方式处理大型的XML文件,它只用到了很少量的内存:

    from xml.etree.ElementTree import iterparse def parse_and_remove(filename, path): path_parts = path.split('/') doc = iterparse(filename, ('start', 'end')) # Skip the root element next(doc) tag_stack = [] elem_stack = [] for event, elem in doc: if event == 'start': tag_stack.append(elem.tag) elem_stack.append(elem) elif event == 'end': if tag_stack == path_parts: yield elem elem_stack[-2].remove(elem) try: tag_stack.pop() elem_stack.pop() except IndexError: pass

    要测试这个函数,只需要找一个大型的XML文件来配合测试即可。这种大型的XML文件常常可以在政府以及数据公开的网站上找到。比如,可以下载芝加哥的坑洞数据库XML。在写作本书时,这个下载文件中有超过100000行的数据,它们按照如下的方式编码:

    <response> <row> <row ...> <creation_date>2012-11-18T00:00:00</creation_date> <status>Completed</status> <completion_date>2012-11-18T00:00:00</completion_date> <service_request_number>12-01906549</service_request_number> <type_of_service_request>Pot Hole in Street</type_of_service_request> <current_activity>Final Outcome</current_activity> <most_recent_action>CDOT Street Cut ... Outcome</most_recent_action> <street_address>4714 S TALMAN AVE</street_address> <zip>60632</zip> <x_coordinate>1159494.68618856</x_coordinate> <y_coordinate>1873313.83503384</y_coordinate> <ward>14</ward> <police_district>9</police_district> <community_area>58</community_area> <latitude>41.808090232127896</latitude> <longitude>-87.69053684711305</longitude> <location latitude="41.808090232127896" longitude="-87.69053684711305" /> </row> <row ...> <creation_date>2012-11-18T00:00:00</creation_date> <status>Completed</status> <completion_date>2012-11-18T00:00:00</completion_date> <service_request_number>12-01906695</service_request_number> <type_of_service_request>Pot Hole in Street</type_of_service_request> <current_activity>Final Outcome</current_activity> <most_recent_action>CDOT Street Cut ... Outcome</most_recent_action> <street_address>3510 W NORTH AVE</street_address> <zip>60647</zip> <x_coordinate>1152732.14127696</x_coordinate> <y_coordinate>1910409.38979075</y_coordinate> <ward>26</ward> <police_district>14</police_district> <community_area>23</community_area> <latitude>41.91002084292946</latitude> <longitude>-87.71435952353961</longitude> <location latitude="41.91002084292946" longitude="-87.71435952353961" /> </row> </row> </response>

    假设我们想编写一个脚本来根据坑洞的数量对邮政编码(ZIP code)进行排序。可以编写如下的代码来实现:

    from xml.etree.ElementTree import parse from collections import Counter potholes_by_zip = Counter() doc = parse('potholes.xml') for pothole in doc.iterfind('row/row'): potholes_by_zip[pothole.findtext('zip')] += 1 for zipcode, num in potholes_by_zip.most_common(): print(zipcode, num)

    这个脚本存在的唯一问题就是它将整个XML文件都读取到内存中后再做解析。在我们的机器上,运行这个脚本需要占据450 MB内存。但是如果使用下面这份代码,程序只做了微小的修改:

    from collections import Counter potholes_by_zip = Counter() data = parse_and_remove('potholes.xml', 'row/row') for pothole in data: potholes_by_zip[pothole.findtext('zip')] += 1 for zipcode, num in potholes_by_zip.most_common(): print(zipcode, num)

    这个版本的代码运行起来只用了7 MB内存——多么惊人的提升啊!

    6.4.3 讨论

    本节中的示例依赖于ElementTree模块中的两个核心功能。首先,iterparse()方法允许我们对XML文档做增量式的处理。要使用它,只需提供文件名以及一个事件列表即可。事件列表由1个或多个start/end,start-ns/end-ns组成。iterparse()创建出的迭代器产生出形式为(event,elem)的元组,这里的event是列出的事件,而elem是对应的XML元素。示例如下:

    >>> data = iterparse('potholes.xml',('start','end')) >>> next(data) ('start', <Element 'response' at 0x100771d60>) >>> next(data) ('start', <Element 'row' at 0x100771e68>) >>> next(data) ('start', <Element 'row' at 0x100771fc8>) >>> next(data) ('start', <Element 'creation_date' at 0x100771f18>) >>> next(data) ('end', <Element 'creation_date' at 0x100771f18>) >>> next(data) ('start', <Element 'status' at 0x1006a7f18>) >>> next(data) ('end', <Element 'status' at 0x1006a7f18>) >>>

    当某个元素首次被创建但是还没有填入任何其他数据时(比如子元素),会产生start事件,而end事件会在元素已经完成时产生。尽管没有在本节示例中出现,start-ns和end-ns事件是用来处理XML命名空间声明的。

    在这个示例中,start和end事件是用来管理元素和标签栈的。这里的栈代表着文档结构中被解析的当前层次(current hierarchical),同时也用来判断元素是否匹配传递给parse_and_remove()函数的请求路径。如果有匹配满足,就通过yield将其发送给调用者。

    紧跟在yield之后的语句就是使得ElementTree能够高效利用内存的关键所在:

    elem_stack[-2].remove(elem)

    这一行代码使得之前通过yield产生出的元素从它们的父节点中移除。因此可假设其再也没有任何其他的引用存在,因此该元素被销毁进而可以回收它所占用的内存。

    这种迭代式的解析以及对节点的移除使得对整个文档的增量式扫描变得非常高效。在任何时刻都能构造出一棵完整的文档树。然而,我们仍然可以编写代码以直接的方式来处理XML数据。

    这种技术的主要缺点就是运行时的性能。当进行测试时,将整个文档先读入内存的版本运行起来大约比增量式处理的版本快2倍。但是在内存的使用上,先读入内存的版本占用的内存量是增量式处理的60倍多。因此,如果内存使用量是更加需要关注的因素,那么显然增量式处理的版本才是大赢家。

    相关资源:python cookbook(第3版)
    最新回复(0)