migrate from ET.parse to etree.iterparse

亡梦爱人 提交于 2019-12-12 01:52:41

问题


Wrote a code to parse .osm file. Spend a lot of time to build a up to 50 rows code but ran into a 'Memory Error' problem. Seems like the best solution is to use interparse() instead of parse().

My question is: how should I change my code (strating of my code)

import xml.etree.ElementTree as ET
tree = ET.parse('file.osm')
root = tree.getroot()

to ( using interparse() method) (not my code)

import xml.etree.ElementTree as etree
context=etree.iterparse('file.osm', events=('start', 'end', 'start-ns', 'end-ns'))

and not to ruin rest of my code (only part of my code)

list=[]
for i in root.findall('node'):  
    lat=i.get('lat')
    lon=i.get('lon')
    dict = {}
    for ii in i:        
        dict['lat']=lat
        dict['lon']=lon     
        key=ii.get('k')
        val=ii.get('v')     
        dict[key]=val       
    if len(dict)>0:
        list.append(dict)

回答1:


tree = ET.iterparse('file.osm')
root = tree.root

this will give you the tree root. from there it is the same as parse



来源:https://stackoverflow.com/questions/35339067/migrate-from-et-parse-to-etree-iterparse

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!