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



本质上,我有一系列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模块看起来很有前景,但我在多个文件中的Find和Replace函数方面遇到了问题。如有任何帮助,我们将不胜感激,谢谢!

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

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

最新更新