開始使用免費開始

在 spaCy 中建立自訂命名實體

如果 spaCy 內建的命名實體不夠用,你可以透過 spaCy 的 entity_ruler pipeline 元件來自訂。

entity_ruler 元件讓你自行建立實體,並將它們加入 spaCy 的 pipeline。

你會先用 nlp.add_pipe() 把這個元件加到現有的 pipeline,並放在 "ner" 元件的 before,讓你的規則先被套用。add_pipe() 會回傳被加入的元件。

接著,你可以在該元件上呼叫 add_patterns(),並傳入一個字典,指定你想用實體標註的文字 pattern。

由於 Acme 是一家科技公司,你決定將 "smartphone" 這個 pattern 標註為 "PRODUCT" 實體標籤。

spaCy 已經匯入,nlp 也已載入 en_core_web_sm 模型。由於修改 pipeline 不會影響已存在的 docs,你會在新元件就位後,從 call_4_channel_2.wav 的轉錄文字重新建立 doc(檔案)。

本練習屬於課程

Python 的口語語言處理

檢視課程

練習說明

  • 將 "entity_ruler" 元件加入 nlp pipeline,放在 "ner" 元件之前,並將其儲存為 ruler。
  • 將 "smartphone" 作為 "pattern" 鍵的值加入。
  • 列印 doc 中的實體屬性。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# Add an entity_ruler component to the pipeline, before ner
ruler = nlp.add_pipe(____, before=____)

# Define pattern for new entity
ruler.add_patterns([{"label": "PRODUCT", "pattern": ____}])

# Recreate the doc so it uses the updated pipeline
doc = nlp(call_4_channel_2_text)

# Test new entity
for entity in doc.____:
  print(entity.text, entity.label_)
編輯並執行程式碼