天天看點

增量式解析大型XML檔案

問題

你想使用盡可能少的記憶體從一個超大的XML文檔中提取資料。

解決方案

任何時候隻要你遇到增量式的資料處理時,第一時間就應該想到疊代器和生成器。 下面是一個很簡單的函數,隻使用很少的記憶體就能增量式的處理一個大型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格式的芝加哥城市道路坑窪資料庫。 在寫這本書的時候,下載下傳檔案已經包含超過100,000行資料,編碼格式類似于下面這樣:

<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>      

假設你想寫一個腳本來按照坑窪報告數量排列郵編号碼。你可以像這樣做:

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      

這個腳本唯一的問題是它會先将整個XML檔案加載到記憶體中然後解析。 在我的機器上,為了運作這個程式需要用到450MB左右的記憶體空間。 如果使用如下代碼,程式隻需要修改一點點:

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      

結果是:這個版本的代碼運作時隻需要7MB的記憶體–大大節約了記憶體資源。

讨論

這一節的技術會依賴 ​

​ElementTree​

​​ 子產品中的兩個核心功能。 第一,​

​iterparse()​

​​ 方法允許對XML文檔進行增量操作。 使用時,你需要提供檔案名和一個包含下面一種或多種類型的事件清單: ​

​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​

​ 事件被用來管理元素和标簽棧。 棧代表了文檔被解析時的層次結構, 還被用來判斷某個元素是否比對傳給函數 parse_and_remove() 的路徑。 如果比對,就利用 yield 語句向調用者傳回這個元素。

在 ​

​yield​

​​ 之後的下面這個語句才是使得程式占用極少記憶體的​

​ElementTree​

​的核心特性:

elem_stack[-2].remove(elem)      

這個語句使得之前由 ​

​yield​

​ 産生的元素從它的父節點中删除掉。 假設已經沒有其它的地方引用這個元素了,那麼這個元素就被銷毀并回收記憶體。