在 spaCy 中使用多重樣式的 EntityRuler
EntityRuler 能讓你把實體加入 doc.ents,並提升命名實體識別的表現。這個練習中,你會將 EntityRuler 元件加入既有的 nlp pipeline,來確保多個實體都能被正確分類。
en_core_web_sm 模型已載入並可作為 nlp 使用。你可以從 example_text 取得範例文字,分別用 nlp 與 doc 來存取 spaCy 模型與 example_text 的 Doc 容器。
本練習屬於課程
使用 spaCy 的自然語言處理
練習說明
- 使用
nlp模型,列印example_text中所有實體的文字與類型所組成的 tuple 清單。 - 定義多個樣式,將小寫的
brother與sisters標註為PERSON標籤。 - 將
EntityRuler元件加入nlppipeline,並把patterns加入該EntityRuler。 - 使用
nlp模型,列印example_text的實體文字與類型所組成的 tuple。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
nlp = spacy.load("en_core_web_md")
# Print a list of tuples of entities text and types in the example_text
print("Before EntityRuler: ", [____ for ____ in nlp(____).____], "\n")
# Define pattern to add a label PERSON for lower cased sisters and brother entities
patterns = [{"label": ____, "pattern": [{"lower": ____}]},
{"label": ____, "pattern": [{"lower": ____}]}]
# Add an EntityRuler component and add the patterns to the ruler
ruler = nlp.____("entity_ruler")
ruler.____(____)
# Print a list of tuples of entities text and types
print("After EntityRuler: ", [(ent.____, ent.____) for ent in nlp(example_text).____])