【问题标题】:How to parse/extract specific values from an input huge file in python?如何从python中的输入大文件中解析/提取特定值?
【发布时间】:2014-10-15 20:34:18
【问题描述】:

我有以下巨大的输入文件(来自 stackexchange 数据集):

 <row Id="659890" PostTypeId="2" ParentId="655986" CreationDate="2009-03-18T20:06:33.720" />
 <row Id="659891" PostTypeId="2" ParentId="659089" CreationDate="2009-03-18T20:07:44.843" /> 

通常,我处理文件的方式是逐行读取:

f = open( "file.txt", "r" )
for line in f:
   print line

但是,对于这种情况,我想逐个处理它。我该怎么做?

此外,我希望能够提取 PostTypeId 的值并将其保存在一个变量中(我也希望对其他值执行相同的操作)。

所以我的问题是:假设数据集真的很大,那么最有效的方法是什么?

【问题讨论】:

  • 到目前为止你尝试了什么?
  • 为此添加注释,如果处理不当,解析数据转储文件(尤其是堆栈溢出)很容易超过系统内存限制。在对这个问题的任何回答中,这应该是一个重要的考虑因素。
  • 我试图手动执行此操作,通过逐行读取并在每行附加一个本地字符串变量,直到该行以“/>”结尾。之后,我试图通过逐字读取字符串并在正确的标记之后打印内容(例如在 PostTypeId=" 和 " 字符之前)来提取值。然后我重新初始化字符串并对下一行执行相同的过程。我知道这是一种非常愚蠢的方法,而且更耗时,但我想这对大文件很有效,因为我正在逐行读取文件(不是 100% 确定)。

标签: python regex parsing


【解决方案1】:

你可以使用xml.etree.ElementTree

import xml.etree.ElementTree as ET
tree = ET.parse(source)
root = tree.getroot()
# Look at each element that has 'row' tag
for row in root.iter('row'):
    print row.get('PostTypeId')

编辑junk after document

with open(someFile, 'r') as data:
    xmlData = '<rows>' + data.read() + '</rows>'
rows = ET.fromstring(xmlData)
for row in rows:
    print row.get('PostTypeId')

【讨论】:

  • 这成功了!但是,我想指出,我需要使用根标签 ... > ... > 将数据包装为“文档元素之后的垃圾”出现错误(比如这里stackoverflow.com/questions/2574894/…)。
  • 啊,不知道文件问题后的垃圾。我编辑了我的答案以包含它。通常当我使用 ElementTree 时,它​​来自一个 xml 文件,所以我没有未包装的数据
【解决方案2】:

如果您确保&lt;tag /&gt; 在每一行上,并考虑到内存,这可能对您有效:

from xml.etree import ElementTree as ET

with open('yourfile', 'r') as f:
    # file is already a generator of lines
    for line in f:
        # use fromstring so you don't even need to wrap with another tag
        tree = ET.fromstring(line)
        # attrib will return all you need in a dict {key:value}
        # you may store this dict, append to a list, write to a file or even database
        print tree.attrib

您的样本结果:

{'PostTypeId': '2', 'CreationDate': '2009-03-18T20:06:33.720', 'Id': '659890', 'ParentId': '655986'}
{'PostTypeId': '2', 'CreationDate': '2009-03-18T20:07:44.843', 'Id': '659891', 'ParentId': '659089'}

【讨论】:

    猜你喜欢
    • 2014-09-15
    • 1970-01-01
    • 2022-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-04
    • 1970-01-01
    • 2020-07-13
    相关资源
    最近更新 更多