Python批量修改xml的节点值

 

最近再用faster-rcnn训练自己的数据,结果发现标签只能用小写字母,其他的都会报错。
大写字母可以修改py-faster-rcnn/tools/../lib/datasets/pascal_voc.py中的代码,
_load_pascal_annotation中将

    cls = self._class_to_ind[obj.find('name').text.lower().strip()]
  • 1

说是去掉lower可行。

但是(重点来了),我的标签里有空格:screw cap
所以我只能修改xml文件中的内容了。
直接上代码:修改<name>中的内容

# coding=utf-8
import os
import os.path
import xml.dom.minidom

#获得文件夹中所有文件
FindPath = '/home/ubuntu/Desktop/myvoc2007/Annotations/'
FileNames = os.listdir(FindPath)
s = []
xml_path = '/home/ubuntu/Desktop/new/'
for file_name in FileNames:
    if not os.path.isdir(file_name):  # 判断是否是文件夹,不是文件夹才打开
        print file_name

    #读取xml文件
    dom = xml.dom.minidom.parse(os.path.join(FindPath,file_name))

    root = dom.documentElement

    # 获取标签对name之间的值
    name = root.getElementsByTagName('name')
    for i in range(len(name)):
        print name[i].firstChild.data
        if name[i] .firstChild.data== 'screw cap':
            name[i].firstChild.data = 'screwnut'
            print '修改后的 name'
            print name[i].firstChild.data
    #将修改后的xml文件保存
    with open(os.path.join(xml_path, file_name), 'w') as fh:
        dom.writexml(fh)
        print('写入name/pose OK!')

猜你喜欢

转载自blog.csdn.net/duanyajun987/article/details/88248606