Python 代码:从文本文件提取实体词
读取train.conll文件并提取词
with open('train.conll', 'r', encoding='utf-8') as f: lines = f.readlines()
words = '' for line in lines: if line.strip(): # 如果不是空行 word, tag = line.strip().split() # 分离出词和标签 if tag.startswith('B-'): # 如果是一个新的实体的开始 words += word # 将这个词加入到当前的实体中 elif tag.startswith('I-'): # 如果是实体的中间部分 words += word elif tag.startswith('E-'): # 如果是实体的结束部分 words += word print(words) # 输出这个实体 words = '' # 清空当前实体
提取出每个词并输出到ci.txt
with open('ci.txt', 'w', encoding='utf-8') as f: for line in lines: if line.strip(): # 如果不是空行 word, tag = line.strip().split() # 分离出词和标签 if tag.startswith('B-'): # 如果是一个新的实体的开始 f.write(word) # 将这个词输出到文件中 elif tag.startswith('I-'): # 如果是实体的中间部分 f.write(word) elif tag.startswith('E-'): # 如果是实体的结束部分 f.write(word + '\n') # 将这个词输出到文件中,并在结尾加上换行符
原文地址: https://www.cveoy.top/t/topic/f2J7 著作权归作者所有。请勿转载和采集!