在此附上**:
import io
import sys
import os
import xml.etree.elementtree as et
##anno_path修改為你存放xml檔案的位置,最後末尾需要加上/
#old_annotation是修要修改的標籤名,new_annotation是修改後的標籤名字
anno_path = '/home/jun/voc2007/annotations/'
old_annotation = '2'
new_annotation = 'word'
del_annotations = ['occlusion']
#replace = true使用替換功能,false使用刪除功能
replace = true
def _main():
filelist = os.listdir(anno_path)
i = 0
if replace == true:
for file in filelist:
n_ = _replace_annotation(file)
if n_ > 0:
i += 1
else:
for file in filelist:
n_ = _del_annotation(file)
if n_ >0:
i += 1
print('the number of xmlfile is :' + str(i))
def _replace_annotation(filepath):
if os.path.exists(anno_path + filepath) == false:
print(filepath+' :not found')
#建立xml樹狀結構
i = 0
while replace_(filepath) == false:
i += 1
return i
def replace_(filepath):
if os.path.exists(anno_path + filepath) == false:
print(filepath+' :not found')
#建立xml樹狀結構
tree = et.parse(anno_path + filepath)
#遍歷xml檔案 查詢'name'
for annoobject in tree.iter():
if 'object' in annoobject.tag:
for element in list(annoobject):
if 'name' in element.tag:
#替換標籤
if element.text == old_annotation:
element.text = new_annotation
print(filepath)
#重新寫入xml,使修改生效
tree.write(anno_path+filepath, encoding="utf-8", xml_declaration=true)
return false
return true
def _del_annotation(filepath):
if os.path.exists(anno_path + filepath) == false:
print(filepath+' :not found')
#建立xml樹狀結構
i = 0
while delete_(filepath) == false:
i += 1
return i
def delete_(filepath):
if os.path.exists(anno_path + filepath) == false:
print(filepath+' :not found')
#建立xml樹狀結構
tree = et.parse(anno_path + filepath)
#遍歷xml檔案 查詢'name'
root = tree.getroot()
for annoobject in root.iter():
if 'object' in annoobject.tag:
for element in list(annoobject):
if 'name' in element.tag:
#刪除標籤
for anno in del_annotations:
if element.text == anno:
#從根節點下刪除第乙個子節點
root.remove(annoobject)
print(filepath)
#重新寫入xml,使修改生效
tree = et.elementtree(root)
tree.write(anno_path+filepath, encoding="utf-8", xml_declaration=true)
return false
return true
if __name__ == '__main__':
_main()
批量修改標籤名
批量修改標籤名,本例批量修改為smoke。import os import os.path from xml.etree.elementtree import parse,element 批量修改xml中內容 def test path annotations xml檔案所在的目錄 files os...
批量修改voc資料集中xml屬性詳解
import os import os.path import xml.dom.minidom c users chenlufei desktop 1234.xml path f sss 路徑 最好路徑下只有xml檔案,有其他檔案容易報錯 files os.listdir path 得到資料夾下所有...
關於VOC資料集遷移後path路徑修改的指令碼
修改xml檔案中的,與實際資料路徑對應 author leo coding utf 8 import os import os.path import xml.dom.minidom file path pic you picture path jpegimages file path you xm...