xml转json-使用ElementTree

# ===== 导入包 =====
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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值