【发布时间】:2015-10-14 20:39:00
【问题描述】:
我有一个 20gb bz2 xml 文件。格式是这样的:
<doc id="1" url="https://www.somepage.com" title="some page">
text text text ....
</doc>
我需要将它处理成这种格式的tsv文件:
id<tab>url<tab>title<tab>processed_texts
在 python 和 java 中最有效的方法是什么,有什么区别(内存效率和速度方面)。基本上我想这样做:
read bz2 file
read the xml file element by element
for each element
retrieve id, url, title and text
print_to_file(id<tab>url<tab>title<tab>process(text))
提前感谢您的回答。
UPDATE1(基于@Andreas 的建议):
XMLInputFactory factory = XMLInputFactory.newFactory();
XMLStreamReader xmlReader = factory.createXMLStreamReader(in);
xmlReader.nextTag();
if (! xmlReader.getLocalName().equals("doc")) {
xmlReader.nextTag(); }
String id = xmlReader.getAttributeValue(null, "id");
String url = xmlReader.getAttributeValue(null, "url");
String title = xmlReader.getAttributeValue(null, "title");
String content = xmlReader.getElementText();
out.println(id + '\t' + content);
问题是我只得到第一个元素。
UPDATE2(我最终使用正则表达式):
if (str.startsWith("<doc")) {
id = str.split("id")[1].substring(2).split("\"")[0];
url = str.split("url")[1].substring(2).split("\"")[0];
title = str.split("title")[1].substring(2).split("\"")[0];
}
else if (str.startsWith("</doc")) {
out.println(uniq_id + '\t' + contect);
content ="";
}
else {
content = content + " " + str;
}
【问题讨论】: