# ===== 导入包 =====
try:
import xml.etree.cElementTree as ET
except ImportError:
import xml.etree.ElementTree as ET
import json
import sys
import io
# ===== 获取 xml 树 =====
rootpath = '数据集'
tree = ET.parse(rootpath + "/" + str(i) + ".xml")
root = tree.getroot() # 获取根节点
# ===== 新建 json 格式数据 =====
xml_info = {}
data = json.loads(json.dumps(xml_info))
# ===== 复制一下 title =====
title = root.find('title')
data['title'] = title.find('text').text
# ===== 没有就写 none =====
data['date'] = "none"
# ===== list和dict就常规操作 =====
entities = []
for j in range(3):
items = root[j][1]
for labelitem in items.findall("LabelItem"):
for entity in labelitem.findall("entities"):
for labelentity in entity.findall("LabelEntity"):
entitytxttemp = labelentity.find("entityTxt").text
entity = {
"type": "",
"mentions": [{
"text": entitytxttemp,
"begin": index_word_begin,
"end": index_word_begin + len(entitytxttemp) - 1,
}]
}
entities.append(entity)
data['entitiy'] = entities
# ===== 写入json文件 =====
with open("output/"+str(i)+".json","w",encoding='utf-8') as f:
jsondata = json.dumps(data, cls=MyEncoder, ensure_ascii = False,indent = 4)
f.write(jsondata)
xml转json-使用ElementTree
最新推荐文章于 2025-04-02 14:03:09 发布