1-5解析xml格式文件,并转化成jsonl格式文件

该文章描述了如何使用Python的ElementTree库解析XML文件EmotionClassficationTest.xml,提取其中的情感信息,如喜欢、高兴等,并将其存储为JSONL格式,便于进一步处理和分析。
摘要由CSDN通过智能技术生成

读取xml格式的文件,提取情感信息,并存储成jsonl格式文件,代码如下:

import xml.etree.ElementTree as ET import json import jsonlines # 解析XML文件 tree = ET.parse('EmotionClassficationTest.xml') root = tree.getroot() # 构建由字典组成的列表 sentences_list = [] output_type={'like':'喜欢','happiness':'高兴','surprise':'惊讶','disgust':'恐惧','fear':'害怕','anger':'生气','sadness':'忧伤','none':'无'} for weibo in root.findall('weibo'): for sentence_elem in weibo.findall('sentence'): opinionated = sentence_elem.get('opinionated') if opinionated == 'Y': value={} value['instruction']='请分析评论的情感色彩,回复积极或者消极' value['input'] = sentence_elem.text.strip() if sentence_elem.text else '' value['output'] = output_type[sentence_elem.get('emotion-1-type')] sentences_list.append(value) # 将列表保存为JSONL文件 with jsonlines.open('outputweibo.jsonl', mode='w') as file: file.write_all(sentences_list) print('处理完成,结果已保存至 outputweibo.jsonl')

import xml.etree.ElementTree as ET
import json
import jsonlines

# 解析XML文件
tree = ET.parse('EmotionClassficationTest.xml')
root = tree.getroot()

# 构建由字典组成的列表
sentences_list = []
output_type={'like':'喜欢','happiness':'高兴','surprise':'惊讶','disgust':'恐惧','fear':'害怕','anger':'生气','sadness':'忧伤','none':'无'}
for weibo in root.findall('weibo'):
    for sentence_elem in weibo.findall('sentence'):
        opinionated = sentence_elem.get('opinionated')
        if opinionated == 'Y':
            value={}
            value['instruction']='请分析评论的情感色彩,回复积极或者消极'
            value['input'] = sentence_elem.text.strip() if sentence_elem.text else ''
            value['output'] = output_type[sentence_elem.get('emotion-1-type')]
            sentences_list.append(value)

# 将列表保存为JSONL文件
with jsonlines.open('outputweibo.jsonl', mode='w') as file:
    file.write_all(sentences_list)
print('处理完成,结果已保存至 outputweibo.jsonl')
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值