【问题标题】:How can I iterate through a list of XML files using Python and append certain fields?如何使用 Python 遍历 XML 文件列表并附加某些字段?
【发布时间】:2021-06-02 11:51:14
【问题描述】:

基本上我有一系列 PASCALVOC 格式的 XML 文件,但注释是错误的,并且偏离了 10 倍。我需要遍历文件并基本上将“0”添加到特定字段(xmax、xmin , ymax 等)。 XML 文件都如下所示:

<folder>VOC2014</folder>
<filename>2014_000001.png</filename>
<source>
    <database>PASCAL VOC Compatible Annotation Database</database>
    <annotation>Department of Electrical Engineering</annotation>
    <image>PASCAL</image>
</source>
<segmented>0</segmented>
<object>
    <name>car</name>
    <bndbox>
        <xmax>592</xmax>
        <xmin>183</xmin>
        <ymax>338</ymax>
        <ymin>1</ymin>
    </bndbox>
    <difficult>0</difficult>
    <occluded>1</occluded>
    <pose>Frontal</pose>
    <truncated>0</truncated>
</object>
<size>
    <depth>1</depth>
    <height>400</height>
    <width>600</width>
</size>

而在这种情况下,我希望将 xmax 附加到 5920,将 xmin 附加到 1830。ElementTree 模块似乎很有希望,但我在跨多个文件的查找和替换功能时遇到了问题。任何帮助将不胜感激,谢谢!

【问题讨论】:

  • 你尝试了什么?你的代码在哪里?你收到错误信息了吗?始终将完整的错误消息(从“Traceback”一词开始)作为文本(不是截图,不是链接到外部门户)有问题(不是评论)。还有其他有用的信息。
  • 首先为单个文件写入函数 - def process(filename) - 然后在带有文件列表的 for-loop 中运行它。

标签: python xml elementtree


【解决方案1】:

您的示例 xml 格式不正确(它需要包装在根元素中),但假设已修复,您可以尝试以下操作:

import xml.etree.ElementTree as ET

bnd = """your xml above, fixed"""

doc = ET.fromstring(dnd)
for d in doc.findall('.//object/bndbox'):
    for line in d.findall('*'):
        line.text= str(int(line.text)*10)
print(ET.tostring(doc).decode())

输出应包含所有 &lt;bndbox&gt; 子节点,其值等于原始值的 10 倍。

【讨论】:

    猜你喜欢
    • 2017-07-28
    • 2023-03-13
    • 2021-09-27
    • 1970-01-01
    • 2014-04-12
    • 2022-01-10
    • 1970-01-01
    • 2021-06-03
    • 2016-01-07
    相关资源
    最近更新 更多