在 python 中工作,我的目标是解析我制作的 XML 文档并创建一个嵌套的列表列表,以便稍后访问它们并解析提要。 XML 文档类似于以下代码片段:
<?xml version="1.0'>
<sources>
<!--Source List by Institution-->
<sourceList source="cbc">
<f>http://rss.cbc.ca/lineup/topstories.xml</f>
</sourceList>
<sourceList source="bbc">
<f>http://feeds.bbci.co.uk/news/rss.xml</f>
<f>http://feeds.bbci.co.uk/news/world/rss.xml</f>
<f>http://feeds.bbci.co.uk/news/uk/rss.xml</f>
</sourceList>
<sourceList source="reuters">
<f>http://feeds.reuters.com/reuters/topNews</f>
<f>http://feeds.reuters.com/news/artsculture</f>
</sourceList>
</sources>
我想要类似嵌套列表的东西,其中最里面的列表将是<f></f>
标签和上面的列表将使用源名称创建。source="reuters"
将会是路透社。从 XML 文档中检索信息不是问题,我正在这样做elementtree
循环检索node.get('source')
问题是我无法生成具有所需名称和不同来源所需的不同长度的列表。我已尝试附加,但不确定如何附加到包含检索到的名称的列表。字典会更好吗?在这种情况下,最佳做法是什么?我怎样才能做到这一点?如果需要更多信息,请发表评论,我一定会添加它。
根据您的描述,带有根据源名称的键和根据提要列表的值的字典可能可以解决问题。
这是构建这样一个野兽的一种方法:
from lxml import etree
from pprint import pprint
news_sources = {
source.attrib['source'] : [feed.text for feed in source.xpath('./f')]
for source in etree.parse('x.xml').xpath('/sources/sourceList')}
pprint(news_sources)
另一个样本,没有lxml
or xpath
:
import xml.etree.ElementTree as ET
from pprint import pprint
news_sources = {
source.attrib['source'] : [feed.text for feed in source]
for source in ET.parse('x.xml').getroot()}
pprint(news_sources)
最后,如果您对列表推导式过敏:
import xml.etree.ElementTree as ET
from pprint import pprint
xml = ET.parse('x.xml')
root = xml.getroot()
news_sources = {}
for sourceList in root:
sourceListName = sourceList.attrib['source']
news_sources[sourceListName] = []
for feed in sourceList:
feedName = feed.text
news_sources[sourceListName].append(feedName)
pprint(news_sources)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)