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 = []
for line in data:
    if line == '\n':
        word = ''.join(words)
        print(word)
        with open('ci.txt', 'a', encoding='utf-8') as f:
            f.write(word + '\n')
        words = []
    else:
        line = line.strip().split()
        if line[1] in tags:
            words.append(line[0])

这段代码实现了以下功能:

  1. 读取CONLL文件:打开名为'train.conll'的文件,并逐行读取数据。
  2. 定义目标标签列表:创建一个包含所有需要提取的标签的列表tags
  3. 遍历数据行:
    • 如果遇到空行,则表示一个实体结束,将words列表中的字符拼接成字符串,打印并写入'ci.txt'文件,然后清空words列表。
    • 如果不是空行,则分割每一行,判断第二个元素(标签)是否在目标标签列表tags中,如果是则将第一个元素(词语)添加到words列表中。

通过这段代码,你可以方便地从CONLL文件中提取出特定标签的实体,并将其保存到txt文件中,方便后续的分析和处理。

Python从CONLL文件中提取特定标签的实体

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

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