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")
添加回答
舉報