因?yàn)轫?xiàng)目做數(shù)據(jù)集,把圖片放在以中文名命名的文件夾中,導(dǎo)致進(jìn)行數(shù)據(jù)擴(kuò)充時(shí)報(bào)錯(cuò)。
如圖,之前紅框內(nèi)的是中文名,現(xiàn)在要改成英文

image.png
修改思路:
1.打開放xml的文件夾
2.獲取相應(yīng)節(jié)點(diǎn)標(biāo)簽的值
3.對值進(jìn)行更改,其中路徑更改使用正則替換
4.保存xml文件
# coding:utf-8
import re
import os
import os.path
import xml.dom.minidom
# path="../xml/"
path = '..\create-dataset\examples\ladder\Annotations'
files = os.listdir(path) # 得到文件夾下所有文件名稱
s = []
for xmlFile in files: # 遍歷文件夾
if not os.path.isdir(xmlFile): # 判斷是否是文件夾,不是文件夾才打開
# xml讀取操作
# 將獲取到的xml文件名送入到dom解析
# 錯(cuò)誤代碼:dom=xml.dom.minidom.parse(xmlFile)
dom = xml.dom.minidom.parse(os.path.join(path, xmlFile))
root = dom.documentElement
###獲取標(biāo)簽對folder/path之間的值
folder = root.getElementsByTagName('folder')
pathNode = root.getElementsByTagName('path')
# 修改相應(yīng)標(biāo)簽的值
for i in range(len(folder)):
print(folder[i].firstChild.data)
a = folder[i].firstChild.data
print(type(a))
folder[i].firstChild.data = 'ladderImages'
print(folder[i].firstChild.data)
for j in range(len(pathNode)):
print(pathNode[j].firstChild.data)
string = pathNode[j].firstChild.data
pathNode[j].firstChild.data = re.sub('梯子', 'ladderImages', string)
print(pathNode[j].firstChild.data)
# 保存修改到xml文件中
with open(os.path.join(path, xmlFile), 'w') as fh:
dom.writexml(fh)
# root.write(fh)
print('恭喜,寫入folder/path成功!')