Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/fsharp/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python lxml etree.parse MemoryAllocation错误_Python_Lxml - Fatal编程技术网

Python lxml etree.parse MemoryAllocation错误

Python lxml etree.parse MemoryAllocation错误,python,lxml,Python,Lxml,我使用lxml etree.parse解析一个巨大的XML文件(大约65MB-300MB)。 当我运行包含以下函数的独立python脚本时,内存分配失败: Error: Memory allocation failed : xmlSAX2Characters, line 5350155, column 16 部分功能代码: def getID(): try: from lxml import etree xml = e

我使用lxml etree.parse解析一个巨大的XML文件(大约65MB-300MB)。 当我运行包含以下函数的独立python脚本时,内存分配失败:

Error:

     Memory allocation failed : xmlSAX2Characters, line 5350155, column 16
部分功能代码:

def getID():
        try:
            from lxml import etree
            xml = etree.parse(<xml_file>)  # here is where the failure occurs
            for element in xml.iter():
                   ...
                   result = <formed by concatenating element texts>
            return result
        except Exception, ex:
            <handle exception>
def getID():
尝试:
从lxml导入etree
xml=etree.parse()#这里是发生故障的地方
对于xml.iter()中的元素:
...
结果=
返回结果
除例外情况外,例如:
奇怪的是,当我在空闲时输入相同的函数,并测试相同的XML文件时,我没有遇到任何MemoryAllocation错误


对这个问题有什么想法吗?提前感谢。

我将使用解析文档,而不是对您使用的任何元素调用
.clear()
;这样可以避免一次性将整个文档加载到内存中

您可以将迭代解析器限制为仅对您感兴趣的标记。如果您只想解析
标记,请告诉您的解析器:

for _, element in etree.iterparse(input, tag='person'):
    # process your person data
    element.clear()

通过清除循环中的元素,可以将其从内存中释放。

iterparse仍将在内存中生成整个树。如果不需要,则需要一个。那么我将如何使用sax解析器呢?@mata:实际上,您可以使用lxml来节省内存,请参阅。将在今晚或明天晚些时候更新。当您关闭IDLE时,脚本是否正确读取XML文件?可能是空闲正在囤积内存。@jaysonpryde您能解决这个问题吗?