python处理xml脚本
import json
import os
from xml.dom.minidom import parse
import xml.dom.minidom
path = '/home/zqf/bridge/VOC2007/Annotations'
original_name = os.listdir(path)
print(original_name)
for i in original_name:
filename=os.path.join(path,i)
bret = filename.endswith(".xml")
if bret:
savename = os.path.splitext(filename)[0]
print(savename)
savename=savename+".txt"
print(filename)
print(savename)
savename=os.path.join(path,savename)
DOMTree = xml.dom.minidom.parse(filename)
collection = DOMTree.documentElement
size = collection.getElementsByTagName("size")
xwidth = size[0].getElementsByTagName('width')[0]
width=xwidth.childNodes[0].data
print(width)
xheight = size[0].getElementsByTagName('height')[0]
height=xheight.childNodes[0].data
print(height)
objects = collection.getElementsByTagName("object")
for object in objects:
bndbox = object.getElementsByTagName('bndbox')[0]
xmin = bndbox.getElementsByTagName('xmin')[0]
x1=xmin.childNodes[0].data
ymin = bndbox.getElementsByTagName('ymin')[0]
y1=ymin.childNodes[0].data
xmax = bndbox.getElementsByTagName('xmax')[0]
x2=xmax.childNodes[0].data
ymax = bndbox.getElementsByTagName('ymax')[0]
y2=ymax.childNodes[0].data
a1=float(x1)/float(width)
b1=float(y1)/float(height)
a2=float(x2)/float(width)
b2=float(y2)/float(height)
retstr='0 '+'%.6f'%a1+' '+'%.6f'%b1+' '+'%.6f'%a2+' '+'%.6f'%b2+'\n'
print(retstr)
with open(savename, 'a') as f:
f.write(retstr)