我有以下巨大的输入文件(来自 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/