使用Microsoft Books.xml https://learn.microsoft.com/en-us/previous-versions/windows/desktop/ms762271(v=vs.85)
第一项的样本。
<catalog>
<book id="bk101">
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<genre>Computer</genre>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
<description>An in-depth look at creating applications
with XML.</description>
</book>
</catalog>试图用一个奇怪的id从id中提取所有的书名。在字典中捕获id和title作为键,值
到目前为止,我有这个工作,除了所有的标题返回作为一个单一的项目列表。
import xml.etree.ElementTree as ET
tree = ET.parse('books.xml')
root = tree.getroot()
data = {}
for child in root.findall('book'):
for k,v in child.items():
for title in child.iter('title'):
if int(v.split('k')[1]) % 2 != 0:
if k not in data:
data[v] = []
data[v].append(title.text)
print(data['bk101'])输出
{'bk101': ["XML Developer's Guide"], 'bk103': ['Maeve Ascendant'], 'bk105': ['The Sundered Grail'], 'bk107': ['Splish Splash'], 'bk109': ['Paradox Lost'], 'bk111': ['MSXML3: A Comprehensive Guide']}期望输出
{'bk101': "XML Developer's Guide", 'bk103': 'Maeve Ascendant', 'bk105': 'The Sundered Grail', 'bk107': 'Splish Splash', 'bk109': 'Paradox Lost', 'bk111': 'MSXML3: A Comprehensive Guide'}如何将标题作为文本而不是列表返回?
注意事项我可以将它们作为文本从我的字典中提取
print(data['bk101'][0])但是,倾向于将它们保存到字典中,作为以后不提取的文本。
编辑我意识到这是因为在检查键是否存在时,我正在创建一个作为默认值的列表。但是,不能将None类型作为占位符来避免列表副作用。
意识到我应该使用fromkeys键,就像在这个答案所以要用键和空值初始化一个dict中
但我如何在循环中做到这一点呢?
发布于 2022-03-27 01:05:05
如果您不期望每本书有多个<title>标记,那么就没有必要使用列表,您可以只分配title.text的值,而不是追加它。此外,当您知道您特别希望使用child.items()属性时,就没有必要对id进行迭代。如果有其他属性,它可能会导致问题,因为它们不会以相同的格式被拆分。
基于以下假设的简化代码是:每个<book>都有一个id和一个<title>子程序(如您的示例XML中所示):
for child in root.findall('book'):
book_id = child.get('id')
if int(book_id.split('k')[1]) % 2 != 0:
data[book_id] = child.find('title').text
print(data)这给出了输出:
{'bk101': "XML Developer's Guide", 'bk103': 'Maeve Ascendant', 'bk105': 'The Sundered Grail', 'bk107': 'Splish Splash', 'bk109': 'Paradox Lost', 'bk111': 'MSXML3: A Comprehensive Guide'}如果<title>可能丢失,find()可以返回None,因此需要附加的If条件。
如果您希望每个<title>有多个<book>标记,最好有一个列表,并在您的问题中使用child.iter('title')。这也将隐式地处理缺少的标题大小写,因为循环中的代码不会运行。
https://stackoverflow.com/questions/71632853
复制相似问题