增量式解析大型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 potholes_by_zip.most_common():
print(zipcode, num)
這個指令碼唯一的問題是它會先將整個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 potholes_by_zip.most_common():
print(zipcode, num)
結果是:這個版本的程式碼執行時只需要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
產生的元素從它的父節點中刪除掉。 假設已經沒有其它的地方引用這個元素了,那麼這個元素就被銷燬並回收記憶體。
對節點的迭代式解析和刪除的最終效果就是一個在文件上高效的增量式清掃過程。 文件樹結構從始自終沒被完整的建立過。儘管如此,還是能通過上述簡單的方式來處理這個XML資料。
這種方案的主要缺陷就是它的執行效能了。 我自己測試的結果是,讀取整個文件到記憶體中的版本的執行速度差不多是增量式處理版本的兩倍快。 但是它卻使用了超過後者60倍的記憶體。 因此,如果你更關心記憶體使用量的話,那麼增量式的版本完勝。