【问题标题】:KeyError while parsing data from .xml file解析 .xml 文件中的数据时出现 KeyError
【发布时间】:2023-03-16 01:27:01
【问题描述】:

我是一个初学者,试图从 .xml 文件中解析一些数据,其结构如下。

<parking id="pucpr">
  <space id="1" occupied="0">
    <rotatedRect>
      <center x="300" y="207" />
      <size w="55" h="32" />
      <angle d="-74" />
    </rotatedRect>
    <contour>
      <point x="278" y="230" />
      <point x="290" y="186" />
      <point x="324" y="185" />
      <point x="308" y="230" />
    </contour>
  </space>
  <space id="2" occupied="0">
    <rotatedRect>
      <center x="332" y="209" />
      <size w="56" h="33" />
      <angle d="-77" />
    </rotatedRect>
    <contour>
      <point x="325" y="185" />
      <point x="355" y="185" />
      <point x="344" y="233" />
      <point x="310" y="233" />
    </contour>
  </space>
.
.
.
</parking>

在不同的文件夹中有数百个这样的文件。我编写了下面的代码来解析所有这些 .xml 文件中的数据。

import xml.etree.ElementTree as ET
import os
import xlsxwriter

data_path = '/Users/jaehyunlee/Desktop/for_test'

# Read full directory and file name in the folder
for path, dirs, files in os.walk(data_path):
    for file in files:
        if os.path.splitext(file)[1].lower() == '.xml': # filtering only for .xml files
            full_path = os.path.join(path, file)

            # Parsing data from .xml file
            tree = ET.parse(full_path)
            root = tree.getroot()

            for space in root.iter('space'):
                car = space.attrib["occupied"]
                car_int = int(car)

当我尝试解析属性“占用”的值时,就会出现问题。当我运行代码时,它返回 KeyError: 'occupied'。 对于其他属性,例如“x”、“y”、“w”、“h”,它工作得非常好。 有人可以帮忙吗?

附言当我单独转换一个 .xml 文件时,不会发生此错误。但是当我尝试迭代文件夹中的所有文件时会发生这种情况。

【问题讨论】:

  • 也许先检查print(space)print(space.attrib)
  • 您检查文件中的数据了吗?也许有&lt;space&gt; 没有occupied。如果没有"occupied",也许你应该检查if "occupied" in space.attrib: 或使用space.attrib.get("occupied", default_value) 来获取默认值
  • 你应该打印文件名,看看哪个文件有问题。
  • @furas 谢谢。我检查了文件,发现其中一些文件没有“占用”属性:)

标签: python xml parsing attributes keyerror


【解决方案1】:

我发现这个KeyError是因为一些文件不包含属性'occupied'而发生的。为了避免这个问题并继续迭代,我在“for”下添加了“if”。

import xml.etree.ElementTree as ET
import os
import xlsxwriter

data_path = '/Users/jaehyunlee/Desktop/for_test'

# Read full directory and file name in the folder
for path, dirs, files in os.walk(data_path):
    for file in files:
        if os.path.splitext(file)[1].lower() == '.xml': # filtering only for .xml files
            full_path = os.path.join(path, file)

            # Parsing data from .xml file
            tree = ET.parse(full_path)
            root = tree.getroot()

            for space in root:
                if 'occupied' in space.attrib:
                    car = space.attrib['occupied'] 
                    car_int = int(car)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-16
    • 2018-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多