使用python创建搜索引擎(仅从XML文件中搜索)

2024-06-01 02:06:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我在一个XML文件中有这样的细节

<note>
<id>51</id>
<Name>Jani</Name>
<city>Frankfurt</city>
<IQ>Intelligent</IQ>
</note>

<note>
<id>71</id>
<Name>Peter</Name>
<city>Paris</city>
<IQ>Average</IQ>
</note>

<note>
<id>81</id>
<Name>Asho</Name>
<city>Paris</city>
<IQ>Intelligent</IQ>
</note>

考虑到这些细节,我想实现一个搜索引擎,让用户能够搜索文件中所有的'Intelligent'人。在

请建议我用python实现它的最佳方法。在


Tags: 文件nameidcityxml细节peternote
2条回答

如果文件很小,他们就去图书馆xml.mindom文件可以给你一个容易转换的数据结构 如果文件比较大,我建议xml.etree.cElementTree在

也可以根据需要准备文件,例如: 制作一个dict(如果使用了所有的数字id,则为list),其中包含有相关数据的元组/列表 然后创建一个包含ID列表的名称、城市和IQ dict,以便:

注[51]=(51,'Jani','Frankfurt','Intelligent')

以及

智商[智能]=(81,51)

等等。。在

使用lxml和XPath:

from StringIO import StringIO
from lxml import etree

xml = """<root>
<note>
<id>51</id>
<Name>Jani</Name>
<city>Frankfurt</city>
<IQ>Intelligent</IQ>
</note>

<note>
<id>71</id>
<Name>Peter</Name>
<city>Paris</city>
<IQ>Average</IQ>
</note>

<note>
<id>81</id>
<Name>Asho</Name>
<city>Paris</city>
<IQ>Intelligent</IQ>
</note>

</root>"""

tree = etree.parse(StringIO.StringIO(xml))
for note in tree.xpath("//note[IQ='Intelligent']"):
    print note.getchildren()[1].tag + "=" + note.getchildren()[1].text

打印:

^{pr2}$

相关问题 更多 >