在Python中解析大型XML文件时出现内存错误

时间:2013-06-22 14:52:23

标签: python xml xml-parsing lxml

我的XML文件如下所示:

<root>
<group from="1", to="100">
    <link target="1"/>
    ...
    <link target="100"/>
</group>
...
</root>

我有6000个<group>元素和5M <link>个元素。我想要一个包含元组(fromto)的字典作为键和<link> s'target属性的列表,但是我得到了一个内存错误代码:

from lxml import etree
from gzip import open as gopen

def extractTargets(fin):
    targets = dict()

    with gopen(fin) as xml:
        context = etree.iterparse(xml, tag="group")

        for event, elem in context:
            targets[(elem.get("from"), elem.get("to"))] = elem.xpath("link/@target")
            elem.clear()

            while elem.getprevious() is not None:
                del elem.getparent()[0]
        del context

2 个答案:

答案 0 :(得分:0)

请尝试以下代码:

lxml.etree

import lxml.etree
from gzip import open as gopen

class GroupDictTarget(object):
    def __init__(self, d):
        self.d = d
    def start(self, tag, attrib):
        if tag == 'group':
            self.group = self.d[attrib['from'], attrib['to']] = []
        elif tag == 'link':
            self.group.append(attrib['target'])
    def close(self):
        pass

def extractTargets(fin):
    with gopen(fin) as xml:
        targets = {}
        parser = lxml.etree.XMLParser(target=GroupDictTarget(targets))
        lxml.etree.parse(xml, parser)
        return targets

xml.parsers.expat

import xml.parsers.expat
from gzip import open as gopen

class GroupDictTarget(object):
    # Same as above

def extractTargets(fin):
    targets = {}
    p = xml.parsers.expat.ParserCreate()
    p.StartElementHandler = GroupDictTarget(targets).start
    with gopen(fin) as f:
        p.ParseFile(f)
    return targets

xml.sax

import xml.sax
from gzip import open as gopen

class GroupDictTarget(object):
    # Same as above

def extractTargets(fin):
    targets = {}
    handler = xml.sax.handler.ContentHandler()
    handler.startElement = GroupDictTarget(targets).start
    with gopen(fin) as f:
        xml.sax.parse(f, handler)
    return targets

答案 1 :(得分:0)

我今天遇到了同样的问题,对我来说,删除“tag”参数后,它才起作用:

context = etree.iterparse(xml)

for event, elem in context:
        if elem.tag = "group":
            targets[(elem.get("from"), elem.get("to"))] = elem.xpath("link/@target")
        elem.clear()

        while elem.getprevious() is not None:
            del elem.getparent()[0]
    del context