我有如下XML文件。
<?xml version="1.0" encoding="UTF-8"?><searching>
<query>query01</query>
<document id="0">
<title>lord of the rings.</title>
<snippet>
this is a snippet of a document.
</snippet>
<url>http://www.google.com/</url>
</document>
<document id="1">
<title>harry potter.</title>
<snippet>
this is a snippet of a document.
</snippet>
<url>http://www.google.com/</url>
</document>
........ #and other documents .....
<group id="0" size="298" score="145">
<title>
<phrase>GROUP A</phrase>
</title>
<document refid="0"/>
<document refid="1"/>
<document refid="84"/>
</group>
<group id="0" size="298" score="55">
<title>
<phrase>GROUP B</phrase>
</title>
<document refid="2"/>
<document refid="13"/>
<document refid="3"/>
</group>
</<searching>>
我想得到上面的组名以及每个组中的文档id(及其标题)是什么。我的想法是将文档id和文档标题存储到字典中,如下所示:
import codecs
documentID = {}
group = {}
myfile = codecs.open("file.xml", mode = 'r', encoding = "utf8")
for line in myfile:
line = line.strip()
#get id from tags
#get title from tag
#store in documentID
#get group name and document reference
而且,我也试过美容组,但对它很陌生。我不知道该怎么办。这是我正在做的代码。
def outputCluster(rFile):
documentInReadFile = {} #dictionary to store all document in readFile
myfile = codecs.open(rFile, mode='r', encoding="utf8")
soup = BeautifulSoup(myfile)
# print all text in readFile:
# print soup.prettify()
# print soup.find+_all('title')
outputCluster("file.xml")
请给我一些建议。 谢谢您。
Elementree在查找XML方面非常出色。 如果您进入文档,它将向您展示如何以多种方式操作XML,包括如何获取标记的内容。文档中的一个示例是:
XML格式:
代码:
你可以很容易地操纵它做你想做的事。
以前的海报是有权利的。etree文档可以在以下位置找到:
https://docs.python.org/2/library/xml.etree.elementtree.html#module-xml.etree.ElementTree
可以帮助你。下面是一个可能会成功的代码示例(部分来自上面的链接):
或者,如果您希望ID存储在group标记中,您可以使用
id = group.get('id')
,而不是搜索所有的refid
你看了Python's XML ^{} 解析器了吗?网上有很多例子。
相关问题 更多 >
编程相关推荐