如何使用Python迭代XML文件列表并附加某些字段?

2024-06-02 05:33:57 发布

您现在位置:Python中文网/ 问答频道 /正文

基本上,我有一系列PASCALVOC格式的XML文件,但是注释是错误的,并且偏离了10倍。我需要遍历这些文件,并在特定字段(xmax、xmin、ymax等)中添加一个“0”。 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模块似乎很有前途,但我在跨多个文件的查找和替换函数方面遇到了问题。任何帮助都将不胜感激,谢谢


1条回答
网友
1楼 · 发布于 2024-06-02 05:33:57

您的示例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())

输出应具有所有<bndbox>子节点,其值等于原始值的10倍

相关问题 更多 >