SpaCy是否有用其标签替换SpaCy NER检测到的实体?例如:我在玩苹果Macbook时正在吃一个苹果。
[我已经使用SpaCy训练了NER模型来检测“水果”实体,并且该模型成功地将第一个“苹果”检测为“水果”,但没有将第二个“苹果”检测到。
我想通过将每个实体替换为其标签来对数据进行后处理,所以我想用“水果”替换第一个“苹果”。句子将为“ 我在玩我的Apple Macbook时正在吃水果。“
如果我仅使用正则表达式,它也会将第二个“ Apple”也替换为“ FRUITS”,这是不正确的。有什么聪明的方法可以做到这一点吗?
谢谢!
实体标签是令牌的属性(请参见here)
import spacy
from spacy import displacy
nlp = spacy.load('en_core_web_lg')
s = "His friend Nicolas is here."
doc = nlp(s)
print([t.text if not t.ent_type_ else t.ent_type_ for t in doc])
# ['His', 'friend', 'PERSON', 'is', 'here', '.']
print(" ".join([t.text if not t.ent_type_ else t.ent_type_ for t in doc]) )
# His friend PERSON is here .
编辑:
为了处理实体可以跨越多个单词的情况,可以改用以下代码:
s = "His friend Nicolas J. Smith is here with Bart Simpon and Fred."
doc = nlp(s)
newString = s
for e in reversed(doc.ents): #reversed to not modify the offsets of other entities when substituting
print(e)
start = e.start_char
end = start + len(e.text)
newString = newString[:start] + e.label_ + newString[end:]
print(newString)
#His friend PERSON is here with PERSON and PERSON.