Skip to main content
 首页 » 编程设计

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

2024年10月25日11xiaohuochai

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