Python XML转Json之XML2Dict的使用方法
1.Json读写方法
defparseFromFile(self,fname): """ OverwrittentoreadJSONfiles. """ f=open(fname,"r") returnjson.load(f) defserializeToFile(self,fname,annotations): """ OverwrittentowriteJSONfiles. """ f=open(fname,"w") json.dump(annotations,f,indent=4,separators=(',',':'),sort_keys=True) f.write("\n")
2.xml文件的工具包XML2Dict
将xml转换成Python本地字典对象,访问子元素和字典常用方法类似,略有不同,使用“.”
注:使用xml2dict库,需要在本地项目添加xml2dict.py,object_dict.py,下载链接
加载xml文件
fromxml2dictimportXML2Dict xml=XML2Dict() r=xml.parse("待处理文件名.xml")
xml示例[voc2007格式]:
VOC2007 AL_00001.JPG 800 1160 3
分析下这个文件的格式:
最外一层被
往里一层是:
#-*-coding:utf-8-*- fromxml2dictimportXML2Dict xml=XML2Dict() r=xml.parse('Annotations/AL_00001.xml') foriteminr.annotation: printitem print'------------' foriteminr.annotation.object: printitem.name,item.bndbox.xmin,item.bndbox.xmax,item.bndbox.ymin,item.bndbox.ymax
执行结果:
object folder size value filename ------------ l_faster270352376503 l_faster262355746871 r_faster412494376486 r_faster411493748862
完整代码[xml2json]
#-*-coding:utf-8-*- fromxml2dictimportXML2Dict importjson importglob defserializeToFile(fname,annotations): """ OverwrittentowriteJSONfiles. """ f=open(fname,"w") json.dump(annotations,f,indent=4,separators=(',',':'),sort_keys=True) f.write("\n") defgetAnnos(file_name="",prefix=''): xml=XML2Dict() root=xml.parse(file_name) #getadictobject anno=root.annotation image_name=anno.filename item={'filename':prefix+image_name,'class':'image','annotations':[]} forobjinanno.object: cls={'l_faster':'C1','r_faster':'C2'}[obj.name] box=obj.bndbox x,y,width,height=int(box.xmin),int(box.ymin),int(box.xmax)-int(box.xmin),int(box.ymax)-int(box.ymin) item['annotations']+=[{ "class":cls, "height":height, "width":width, "x":x, "y":y }] returnitem if__name__=='__main__': annotations=[] anno_name='AR_001-550.json' files=glob.glob('Annotations/AR_*.xml') files=sorted(files) #printfiles.sort() forfilenameinfiles: item=getAnnos(filename,prefix='TFS/JPEGImages/') printitem print'-----------------' annotations+=[item]#"xmls/AL_00001.xml" serializeToFile(anno_name,annotations)
以上这篇PythonXML转Json之XML2Dict的使用方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。