python - 编辑 xml Annotations 数据集的标签
问题描述
我有一个具有以下注释结构的数据集:
`<annotation>
<folder>images</folder>
<filename>maksssksksss0.png</filename>
<size>
<width>512</width>
<height>366</height>
<depth>3</depth>
</size>
<segmented>0</segmented>
<object>
<name>without_mask</name>
<pose>Unspecified</pose>
<truncated>0</truncated>
<occluded>0</occluded>
<difficult>0</difficult>
<bndbox>
<xmin>79</xmin>
<ymin>105</ymin>
<xmax>109</xmax>
<ymax>142</ymax>
</bndbox>
</object>
<object>
<name>with_mask</name>
<pose>Unspecified</pose>
<truncated>0</truncated>
<occluded>0</occluded>
<difficult>0</difficult>
<bndbox>
<xmin>185</xmin>
<ymin>100</ymin>
<xmax>226</xmax>
<ymax>144</ymax>
</bndbox>
</object>
<object>
<name>without_mask</name>
<pose>Unspecified</pose>
<truncated>0</truncated>
<occluded>0</occluded>
<difficult>0</difficult>
<bndbox>
<xmin>325</xmin>
<ymin>90</ymin>
<xmax>360</xmax>
<ymax>141</ymax>
</bndbox>
</object>
`
我想做的是将所有对象标签“with_mask”编辑为“face_mask”,并从所有数据集文件中删除所有对象标签“without_mask”。关于从哪里开始的任何提示?图书馆之类的
解决方案
查看 lxml 库并从那里导入 etree。对于搜索,您可以使用 .findall() 和 .find()。您还应该看看基本的 xpath 约束是如何工作的。要从树中删除元素,您可以使用 .remove 函数。如果你把它们放在一起,它可能看起来像这样:
from lxml import etree
#Open you xml
tree = etree.parse("yourxml.xml")
root = tree.getroot()
#Find all objects in your tree
for obj in root.findall('.//object'):
# Get the first child of the object which is called name
name = obj.find("name")
# Use .txt to access the value
if name.text == "with_mask":
# Change the text
obj.attrib["name"] = "face_mask"
if name.text == "without_mask":
#Remove the object from the tree
root.remove(obj)
# Write the tree
with open('yourxml2.xml', 'wb') as f:
tree.write(f)
推荐阅读
- javascript - 在 Heroku 上构建之前如何在项目上运行 javascript 代码
- keras - Keras 模型嵌套在自定义 Keras 层内
- swift - 使用 MKLocalSearch 填充 UITableView
- javascript - 阻止 SocketIO 重新连接,一旦使用不同的地址建立成功的连接
- python - 调用 super 的 forward() 方法
- javascript - 如何从输入中执行 JavaScript 代码
- amazon-web-services - AWS Cloudformation - 如何使用 If Else 条件
- ag-grid - 如何获取 cellEditorSelector 值
- c# - 优化 TreeView 方法
- intellij-idea - 通过 Intellij 中的快捷键和菜单的代码格式