在python中解析Solr输出

2024-04-26 04:04:08 发布

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

我正在尝试解析表单的solr输出:

<doc>
<str name="source">source:A</str>
<str name="url">URL:A</str>
<date name="p_date">2012-09-08T10:02:01Z</date>
</doc>
<doc>
<str name="source">source:B</str>
<str name="url">URL:B</str>
<date name="p_date">2012-08-08T11:02:01Z</date>
</doc>

我热衷于使用beautifulsstonesoup(beautifulsttonesoup的版本;我认为在BS4之前)来解析文档。 我使用了漂亮的汤来解析HTML,但是有些时候我无法找到一种有效的方法来提取标记的内容。在

我写过:

^{pr2}$

我确实感觉到,我可以通过我的方式强行通过它来获得输出(比如说“再加一次汤”),但我希望有一个有效的解决方案来提取数据。 我需要的输出是:

source:A
URL:A
2012-09-08T10:02:01Z
source:B
URL:B
2012-08-08T11:02:01Z

谢谢


Tags: name文档版本url表单sourcedatedoc
2条回答

请改用XML解析器执行任务;^{}包含在Python中:

from xml.etree import ElementTree as ET

# `ET.fromstring()` expects a string containing XML to parse.
# tree = ET.fromstring(solrdata)  
# Use `ET.parse()` for a filename or open file object, such as returned by urllib2:
ET.parse(urllib2.urlopen(url))

for doc in tree.findall('.//doc'):
    for elem in doc:
        print elem.attrib['name'], elem.text

你一定要使用这种特殊的输出格式吗?Solr支持现成的Python输出格式(至少在版本4中),只需在查询中使用wt=Python。在

相关问题 更多 >

    热门问题