从Conll文件提取特定标签的词语

本代码演示如何使用Python从Conll格式文件中提取特定标签的词语,例如地名标签。

代码实现python# 打开文件with open('train.conll', 'r', encoding='utf-8') as f: data = f.readlines()

定义需要提取的标签tags = ['B-prov', 'I-prov', 'E-prov', 'B-city', 'I-city', 'E-city', 'B-district', 'I-district', 'E-district', 'B-town', 'I-town', 'E-town', 'B-community', 'I-community', 'E-community', 'B-village_group', 'E-village_group', 'B-road', 'I-road', 'E-road', 'B-subpoi', 'I-subpoi', 'E-subpoi']

定义变量存储提取出的词语words = []current_word = ''

遍历数据for line in data: # 去除空格 line = line.strip() # 如果行为空则跳过 if not line: if current_word: words.append(current_word) current_word = '' continue # 将行按空格分隔成列表 line_list = line.split() # 获取词和标签 word, tag = line_list[0], line_list[-1] # 如果标签在需要提取的标签列表中,则将词添加到words变量中 if tag in tags: current_word += word else: if current_word: words.append(current_word) current_word = ''

处理最后一个词语if current_word: words.append(current_word)

将提取出的词语按换行符分开并写入文件with open('ci.txt', 'w', encoding='utf-8') as f: f.write('

'.join(words))

示例

假设 train.conll 文件包含以下内容:text湖 B-prov北 I-prov省 E-prov松 B-district滋 I-district市 E-district八 B-town宝 I-town镇 E-town丝 B-community线 I-community潮 I-community村 E-community五 B-village_group组 E-village_group秋 B-road实 I-road路 E-road运 B-subpoi营 I-subpoi部 E-subpoi

运行代码后,ci.txt 文件将包含以下内容:

湖北省松滋市八宝镇丝线湖村五组秋实路运营部

说明

  • 代码中定义的 tags 列表包含了需要提取的标签。* 代码会遍历Conll文件的每一行,并根据标签判断是否提取词语。* 提取出的词语存储在 words 列表中,最后写入到 ci.txt 文件中。
Python从Conll文件中提取特定标签的词语

原文地址: https://www.cveoy.top/t/topic/f2JD 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录