[英]How can I iterate through a list of XML files using Python and append certain fields?
本質上,我有一系列 PASCALVOC 格式的 XML 文件,但注釋是錯誤的,並且相差 10 倍。我需要遍歷文件並基本上將“0”添加到特定字段(xmax、xmin、ymax、 ETC。)。 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 模塊似乎很有希望,但我在跨多個文件的查找和替換功能時遇到了問題。 任何幫助將不勝感激,謝謝!
您的示例 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())
output 的所有<bndbox>
子節點的值應等於原始值的 10 倍。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.