【问题标题】:Extracting start and end indices of a token using spacy使用 spacy 提取令牌的开始和结束索引
【发布时间】:2023-02-01 05:22:22
【问题描述】:
标签:
python
python-3.x
spacy
【解决方案1】:
您可以在纯 python 中使用 re 执行此操作:
s="This is a sentence written in english by a native English speaker."
import re
[(i.start(), i.end()) for i in re.finditer('ENGLISH', s.upper())]
#output
[(30, 37), (50, 57)]
你也可以在 spacy 中做:
import spacy
nlp=spacy.load("en_core_web_sm")
doc=nlp("This is a sentence written in english by a native English speaker.")
for ent in doc.ents:
if ent.text.upper()=='ENGLISH':
print(ent.start_char,ent.end_char)
【解决方案2】:
使用您链接的答案中的想法,您可以做这样的事情
from spacy.lang.en import English
nlp = English()
s = nlp("This is a sentence written in english by a native English speaker")
boundaries = []
for idx, i in enumerate(s[:-1]):
if i.text.lower() == "english":
boundaries.append((i.idx, s[idx+1].idx-1))
【解决方案3】:
您可以简单地使用 SpaCy 这样做,它不需要对最后一个标记进行任何检查(与@giovanni 的解决方案不同):
def get_char_span(input_txt):
doc = nlp(input_txt)
for i, token in enumerate(doc):
start_i = token.idx
end_i = start_i + len(token.text)
# token span and the token
print(i, token)
# character span
print((start_i, end_i))
# veryfying it in the original input_text
print(input_txt[start_i:end_i])
inp = "My name is X, what's your name?"
get_char_span(inp)