python-3.x - 查找和替换 xml 子标签文本的 Python 代码
问题描述
我在下面有一个 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'
解决方案
在第一个代码片段中,您使用未定义的变量,例如xmin
in n_xmin=str(xmin-x)
。
在第二个片段中,您尝试找到xmin
根的每个孩子的孩子。XML 文档中不存在此类元素。xmin
元素位于层次结构的更下方。
以下代码将 10 添加到xmin
、ymin
、xmax
和ymax
元素的整数值。
import xml.etree.ElementTree as ET
tree = ET.parse('leuko32.xml')
wanted = ["xmin", "ymin", "xmax", "ymax"]
for elem in tree.iter():
if elem.tag in wanted:
elem.text = str(int(elem.text) + 10)
tree.write('C2.xml')
推荐阅读
- chromecast - 没有“检查”链接 chromecast 4th gen
- google-sheets - 参数必须是范围错误 Google 表格
- node.js - 使用 multer、reactjs、nodejs 上传图片
- haskell - Haskell:带列表的二叉搜索树
- sql - 如何使用 Perl 将 blob 和时间戳插入 Oracle 中的表中?
- python - NGINX + Certbot + Flask - CORS 问题
- filter - 活动 x 控制按钮将自动筛选行(特定单元格)数据从一个工作表复制到另一个工作表
- angular - Chart.js:如何手动设置行高
- python - 无法导入 pandas_ml
- amazon-web-services - 如何正确设置授权方:aws_iam 基于无服务器框架中的舞台环境?