在 spaCy 建立自訂的命名實體
如果 spaCy 內建的命名實體不夠用,你可以使用 spaCy 的 EntityRuler() 類別自訂實體。
EntityRuler() 允許你建立自己的實體,並新增到 spaCy 的 pipeline。
你會先建立一個 EntityRuler() 執行個體,並將目前的 pipeline(nlp)傳入。
接著,你可以在該執行個體上呼叫 add_patterns(),並傳入一個字典,指定你想標記為實體的文字 pattern。
設定好 pattern 後,就可以用 add_pipe() 把它加入 nlp 的 pipeline。
由於 Acme 是一家科技公司,你決定將 pattern "smartphone" 標記為 "PRODUCT" 實體標籤。
spaCy 已經匯入,且已經有一個 doc,其中包含自 call_4_channel_2.wav 轉錄而來的文字(file)。
本練習屬於課程
Python 的口語語言處理
練習說明
- 從
spacy.pipeline匯入EntityRuler。 - 將
"smartphone"加入為"pattern"金鑰的值。 - 將
EntityRuler()執行個體ruler加入nlp的 pipeline。 - 列印
doc中包含的實體屬性。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Import EntityRuler class
from spacy.pipeline import ____
# Create EntityRuler instance
ruler = EntityRuler(nlp)
# Define pattern for new entity
ruler.add_patterns([{"label": "PRODUCT", "pattern": ____}])
# Update existing pipeline
nlp.add_pipe(____, before="ner")
# Test new entity
for entity in doc.____:
print(entity.text, entity.label_)