【发布时间】:2019-07-23 05:53:33
【问题描述】:
我在下面有一个 xml 文件,我需要通过添加 10 或对其执行一些算术运算来查找和替换 xmin、ymin、xmax、ymax 标签。我是带有 xml 文件的 python 新手。
xml文件如下:
<annotation>
<folder>stomatitis</folder>
<filename>stomatitis427.jpg</filename>
<path>/Volumes/Windows/tongue-img/stomatitis/stomatitis427.jpg</path>
<source>
<database>Unknown</database>
</source>
<size>
<width>2992</width>
<height>2000</height>
<depth>3</depth>
</size>
<segmented>0</segmented>
<object>
<name>stomatitis</name>
<pose>Unspecified</pose>
<truncated>0</truncated>
<difficult>0</difficult>
<bndbox>
<xmin>1324</xmin>
<ymin>677</ymin>
<xmax>1404</xmax>
<ymax>783</ymax>
</bndbox>
</object>
<object>
<name>stomatitis</name>
<pose>Unspecified</pose>
<truncated>0</truncated>
<difficult>0</difficult>
<bndbox>
<xmin>1610</xmin>
<ymin>643</ymin>
<xmax>1670</xmax>
<ymax>720</ymax>
</bndbox>
</object>
</annotation>
我需要替换所有 xmin,ymin,xmax,ymax 标签文本值并保存更新的 xml 文件。 我试过这段代码,但它给出了错误:
import xml.etree.ElementTree as ET
tree = ET.parse('/Users/sripdeep/Desktop/Tongue_Cancer/leuko32.xml')
root = tree.getroot()
x=10
n_xmin=str(xmin-x)
n_ymin=str(ymin-x)
n_xmax=str(xmax-x)
n_ymax=str(ymax-x)
for elem in root.getiterator():
try:
elem.text = elem.text.replace(str(xmin),n_xmin)
elem.text = elem.text.replace(str(ymin),n_ymin)
elem.text = elem.text.replace(str(xmax),n_xmax)
elem.text = elem.text.replace(str(ymax),n_ymax)
except AttributeError:
pass
tree.write(open('C2.xml', 'wb'))
新创建的 xml 文件中的值不会更新。
我也试过这个代码:
import xml.etree.ElementTree as ET
tree = ET.parse('/Users/sripdeep/Desktop/Tongue_Cancer/leuko32.xml')
root = tree.getroot()
for i in root:
print (i.find("xmin").text)
这也给出了错误:
print (i.find("xmin").text)
AttributeError: 'NoneType' object has no attribute 'text'
【问题讨论】:
-
这看起来非常简单。错误消息告诉您问题所在。您已经知道如何将事物转换为
str类型,因为您是在代码中进行的。这里有什么困难? -
我认为 elem.text = elem.text.replace(xmin,n_xmin) 仅用于替换文本值,但在我的情况下我有整数,我正在执行一些操作
-
我试过 (stackoverflow.com/questions/41089578/…) 但它显示错误
-
@jpmc26 错误已解决,但新值未在 xml 文件中更新