2016-02-13 89 views
0

我有一个相当大的XML文件,大小约为3GB,我想使用'xmltodict'实用程序以流模式进行解析。我已经遍历每个项目的代码,并形成一个字典项目并附加到内存中的字典,最终被转储为json文件。使用'xmltodict'模块解析大型XML文件导致OverflowError

,我有以下的小XML数据集完美的工作:

import xmltodict, json 
    import io 

    output = [] 

    def handle(path, item): 
     #do stuff 
     return 

    doc_file = open("affiliate_partner_feeds.xml","r") 
    doc = doc_file.read()   
    xmltodict.parse(doc, item_depth=2, item_callback=handle) 

    f = open('jbtest.json', 'w') 
    json.dump(output,f) 

在一个大的文件,我得到如下:

Traceback (most recent call last): 
    File "jbparser.py", line 125, in <module> 
    **xmltodict.parse(doc, item_depth=2, item_callback=handle)** 
    File "/usr/lib/python2.7/site-packages/xmltodict.py", line 248, in parse 
    parser.Parse(xml_input, True) 
    OverflowError: size does not fit in an int 

内xmltodict.py异常的具体位置是:

def parse(xml_input, encoding=None, expat=expat, process_namespaces=False, 
      namespace_separator=':', **kwargs): 

     handler = _DictSAXHandler(namespace_separator=namespace_separator, 
            **kwargs) 
     if isinstance(xml_input, _unicode): 
      if not encoding: 
       encoding = 'utf-8' 
      xml_input = xml_input.encode(encoding) 
     if not process_namespaces: 
      namespace_separator = None 
     parser = expat.ParserCreate(
      encoding, 
      namespace_separator 
     ) 
     try: 
      parser.ordered_attributes = True 
     except AttributeError: 
      # Jython's expat does not support ordered_attributes 
      pass 
     parser.StartElementHandler = handler.startElement 
     parser.EndElementHandler = handler.endElement 
     parser.CharacterDataHandler = handler.characters 
     parser.buffer_text = True 
     try: 
      parser.ParseFile(xml_input) 
     except (TypeError, AttributeError): 
      **parser.Parse(xml_input, True)** 
     return handler.item 

任何方法来解决这个问题? AFAIK,xmlparser对象不会暴露给我玩,并将'int'更改为'long'。更重要的是,这里究竟发生了什么? 真的很感谢这方面的任何线索。谢谢!

回答

0

尝试使用marshal.load(file)或marshal.load(sys.stdin)以反序列化文件(或将其用作流)而不是将整个文件读入内存,然后将其解析为整个。

这里是一个example

>>> def handle_artist(_, artist): 
...  print artist['name'] 
...  return True 
>>> 
>>> xmltodict.parse(GzipFile('discogs_artists.xml.gz'), 
...  item_depth=2, item_callback=handle_artist) 
A Perfect Circle 
Fantômas 
King Crimson 
Chris Potter 
... 

STDIN:

import sys, marshal 
while True: 
    _, article = marshal.load(sys.stdin) 
    print article['title'] 
+0

感谢输入! – chetfaker