gpt4 book ai didi

python - 为什么我在遍历字典时会出错

转载 作者:行者123 更新时间:2023-12-01 07:11:05 25 4
gpt4 key购买 nike

我是 Python 的初学者,很难理解为什么在迭代从 XML 文件获取的字典时,当我尝试搜索所需的键时出现错误。我还应该提到,我仍然得到结果想要,但不知何故我不断收到错误。

    import os
import shelve
import xml.etree.ElementTree as et

shelfFile = shelve.open('xml_data')
base_path = os.path.dirname(os.path.realpath(__file__))

xml_file = os.path.join(base_path, "data\\nrm_icg_catalog.xml")

tree = et.parse(xml_file)

root = tree.getroot()

elements = ['Name','WBS']

for child in root:
for itemGroup1 in child:
for item in elements:
print(itemGroup1.attrib[item])

带有错误消息的结果:

Facilitating Works
0
Substructure
1
Superstructure
2
Internal Finish
3
Fittings
4
Services
5
Prefabs
6
Works to Existing Building
7
External Works
8
MC Prelims
9
MC OH and P
10
Traceback (most recent call last):
File "c:/Users/Dodzi Agbenorku/OneDrive/Training Files/Programming Lessons/Python/xmlExcel/app.py", line 22, in <module>
print(itemGroup1.attrib[item])
KeyError: 'Name'

这是我正在使用的 xml 文件的一小部分:

<?xml version="1.0" encoding="utf-8"?>
<Takeoff xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="http://download.autodesk.com/us/navisworks/schemas/nw-TakeoffCatalog-10.0.xsd">
<Catalog>
<ItemGroup Name="Facilitating Works" WBS="0" CatalogId="32b4ab2d-6fe8-4c45-9872-c8ea68c0c4de">
<ItemGroup Name="Hazardous Materials" WBS="1" CatalogId="2fdb6bd1-b2d1-4167-a74d-da818183a156">
<ItemGroup Name="Material Removal" WBS="1" CatalogId="ccc8a515-4152-400c-a72e-6fd78561325e">
<Item Name="Material Details" WBS="1" Transparency="0.3" Color="-15161029" LineThickness="0.1" CatalogId="c0a7de26-6bc3-491e-b3c7-3ff5b560eeaf">
<VariableCollection>
<Variable Name="Length" Formula="=ModelLength" Units="Meter" />
<Variable Name="Width" Formula="=ModelWidth" Units="Meter" />
<Variable Name="Thickness" Formula="=ModelThickness" Units="Meter" />
<Variable Name="Height" Formula="=ModelHeight" Units="Meter" />
<Variable Name="Perimeter" Formula="=ModelPerimeter" Units="Meter" />
<Variable Name="Area" Formula="=ModelArea" Units="SquareMeter" />

任何帮助将不胜感激。

最佳答案

发生错误的原因是对于某些节点,Name不在 attrib 中这是一本字典。

而不是 itemGroup1.attrib[item] ,使用itemGroup1.attrib.get(item) 。它将返回值 None如果key不存在,也不会抛出错误。

关于python - 为什么我在遍历字典时会出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58211952/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com