python - 如何从 python 中的输入大文件中解析/提取特定值?

标签 python regex parsing

我有以下巨大的输入文件(来自 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 的值并将其保存在变量中(我也想对其他值执行相同的操作)。

所以我的问题是:假设数据集可能非常巨大,最有效的方法是什么?

最佳答案

您可以使用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')

编辑文档后的垃圾

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

关于python - 如何从 python 中的输入大文件中解析/提取特定值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26391624/

相关文章:

regex - 使用正则表达式提取文本模式

json - 如何在 Akka HTTP 中将 `text/plain` 解码为 JSON

python - 将 CSV 数据流转换为 Pandas DataFrame (Python 2.7)

python - Azure 中的调度容器

python - 为什么Flood Fill算法超出了Leetcode最大递归限制?

parsing - Z3 C++,如何解析smt-competition unsat核心实例

java - NO_MODIFICATION_ALLOWED_ERR : An attempt is made to modify an object where modifications are not allowed

python - 将输出文件添加到 Python 扩展

python - 用于在所有空格处拆分的正则表达式 Python

html - 正则表达式查找没有 alt =".#"的 <img/> 标签