首页 > 解决方案 > Python:从字符串索引中获取标记和 NER 标签

问题描述

我有一个字符串以及该字符串的字典中的标签信息。

string = "Steve works in Meta Graphics"
tags = {"tags": [(0, 4, "PER"), (15, 27, "ORG")]}

我需要使用此信息并生成字符串的以下表示。

string_tag_tuples = [("Steve", "PER"), ("works", "O"), ("in", "O"), ("Meta Graphics", "ORG")]

从提供的信息中获取标记及其相关标记更容易labels,但是,如何将O标记分配给字符串中的其他标记并获得所需的输出?

标签: python

解决方案


我会分两个步骤来做。首先,识别文本的标记部分并将其他部分存储为字符串。然后,将存储为字符串的所有内容转换为带有"0".

string = "Steve works in Meta Graphics"
tags = {"tags": [(0, 4, "PER"), (15, 27, "ORG")]}

## Recognize the tagged strings:

tags['tags'] = sorted(tags['tags'])
ct = 0
i = 0
result = []
cs = ''
while not i >= len(string):
    if i in range(tags['tags'][ct][0],tags['tags'][ct][1]):
        if len(cs)>0:result.append(cs)
        cs = ''
        result.append((string[tags['tags'][ct][0]:tags['tags'][ct][1]+1],tags['tags'][ct][2]))
        i=tags['tags'][ct][1]
        ct=+1
    else:
        cs+=string[i]
    i+=1
if len(cs)>0:result.append(cs)

print('First step:',result)

## Tag the untagged portions of the list:

final_result = []
for e in result:
    if type(e)==tuple:
        final_result.append(e)
    else:
        words = e.split(' ')
        for w in words:
            if len(w)>0: final_result.append((w,'0'))

print('Second step:',final_result)

该程序的输出将是:

First step: [('Steve', 'PER'), ' works in ', ('Meta Graphics', 'ORG')]
Second step: [('Steve', 'PER'), ('works', '0'), ('in', '0'), ('Meta Graphics', 'ORG')]

推荐阅读