python - 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
标记分配给字符串中的其他标记并获得所需的输出?
解决方案
我会分两个步骤来做。首先,识别文本的标记部分并将其他部分存储为字符串。然后,将存储为字符串的所有内容转换为带有"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')]
推荐阅读
- c# - JetBrains Rider IDE 不会重定向来自文件的输入
- botframework - Bot Framework 网络聊天阅读更多功能
- python - 列表中列表的cumsum
- scala - 使用窗口函数对行进行排名
- angular - @viewchild 下拉菜单在 ngAfterViewInit 中未定义
- ios - 在文件应用程序 iOS 13 中显示 UIDocuments
- css - CSS:如何更改圆笔画填充角度(从左填充而不是从右填充)
- querydsl - 在父子表上使用谓词多个条件的Querydsl
- mysql - 从这个数据库模式中获取用户位置的查询是什么?
- sass - 是否可以使用 less 定义自定义主题角度材质?