本文主要是介绍python写入csv/xlsx文件--三元组,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
写入csv文件
import re
import csv
def get_entity_and_ralation_csv(src_preds, src_preds_outputs, tgt):f1 = open(src_preds, 'r', encoding='utf-8')f2 = open(src_preds_outputs, 'r', encoding='utf-8')g = open(tgt, 'w', newline='')#不用写utf-8csv_writer = csv.writer(g)csv_writer.writerow(["实体","关系","实体"])lines_f1 = f1.readlines()lines_f2 = f2.readlines()file_len = len(lines_f1)i = 0while i < file_len:text = lines_f1[i].strip('\ufeff\n').replace(' ','')relation = lines_f2[i],strip('\ufeff\n')# e1_start = text.index('<e1>')# e2_end = text.index('</e1>')# e1_start = text.index('<e2>')# e2_end = text.index('</e2>')e1 = re.findall(r"<e1>(.+?)</e1>")e2 = re.findall(r"<e2>(.+?)</e2>")e1 = e1.pop()e2 = e2.pop()if relation != 'Other':csv_writer.writerow([e1,relation,e2])i += 1
写入xlsx文件
import os
import openpyxl as xl
def get_entity_and_ralation_csv(src_preds, src_preds_outputs, tgt):f1 = open(src_preds, 'r', encoding='utf-8')f2 = open(src_preds_outputs, 'r', encoding='utf-8')if os.path.exists(tgt):workbook = xl.load_workbook(tgt)else:workbook = xl.Workbook()workbook.save(tgt)sheet = workbook.activeheaders = ["实体","关系","实体"]sheet.append(headers)lines_f1 = f1.readlines()lines_f2 = f2.readlines()file_len = len(lines_f1)i = 0while i < file_len:text = lines_f1[i].strip('\ufeff\n').replace(' ','')relation = lines_f2[i],strip('\ufeff\n')# e1_start = text.index('<e1>')# e2_end = text.index('</e1>')# e1_start = text.index('<e2>')# e2_end = text.index('</e2>')e1 = re.findall(r"<e1>(.+?)</e1>")e2 = re.findall(r"<e2>(.+?)</e2>")e1 = e1.pop()e2 = e2.pop()data = [e1,relation,e2]if relation != 'Other':sheet.append(data)i += 1workbook.save(tgt)f1.close()f2.close()
1、src_preds中每行是一句话,其中两个实体分别被特殊字符分割,如:
一种<e1>育苗纸容器机</e1>,包括<e2>导向机构</e2>、分切机构、切虚线机构、印胶机构、甩刀机构和送纸机构。
2、src_preds_outputs每行为一个词,对应src_preds每句话中两个实体的关系,如:
Whole-Component(e1,e2)
3、 tgt存储三元组
这篇关于python写入csv/xlsx文件--三元组的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!