1 回答
TA贡献1852条经验 获得超1个赞
您在索引 0-1 处寻找一个评估为 -1 的标记,这是最后一个标记。
我建议使用该Token.nbor方法在跨度之前查找第一个标记,如果不存在先前的标记,则将其设置为 None 或空字符串。
import spacy
from spacy.matcher import Matcher
# Loading language model
nlp = spacy.load("en_core_web_md")
# Initialising with shared vocab
matcher = Matcher(nlp.vocab)
# Adding statistical predictions
matcher.add("DOG", None, [{"LOWER": "white"}, {"LOWER": "shepherd"}]) # searching for white shepherd
doc = nlp("white shepherd dog")
for match_id, start, end in matcher(doc):
span = doc[start:end]
print("Matched span: ", span.text)
try:
nbor_tok = span[0].nbor(-1)
print("Previous token:", nbor_tok, nbor_tok.pos_)
except IndexError:
nbor_tok = ''
print("Previous token: None None")
添加回答
举报