開始使用免費開始

在 spaCy 中使用 EntityRuler 的 RegEx

規則運算式(Regular expressions,簡稱 RegEx)用於以規則為基礎的資訊擷取,能處理複雜的字串比對樣式。RegEx 可用來擷取樣式,或把字串中符合的樣式替換成其他樣式。在本練習中,你會使用 spaCyEntityRuler,找出指定 text 中的電子郵件地址。

spaCy 套件已經匯入可供你使用。你可以使用 \d 來比對代表任一 0 到 9 數字的中介字元樣式。

spaCy 的樣式可以把 REGEX 當作屬性。在這種情況下,樣式的結構為 [{"TEXT": {"REGEX": "<a given pattern>"}}]

本練習屬於課程

使用 spaCy 的自然語言處理

檢視課程

練習說明

  • 定義一個樣式,用於 EntityRuler 比對 8888888888 這種形式的電話號碼。
  • 載入空白的 spaCy 英文模型,並將 EntityRuler 元件加入管線。
  • 將編譯好的樣式加入 EntityRuler 元件。
  • 執行模型,並列印給定 text 中實體的文字與型別所組成的 tuple。

動手互動練習

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

text = "Our phone number is 4251234567."

# Define a pattern to match phone numbers
patterns = [{"label": "PHONE_NUMBERS", "pattern": [{"TEXT": {"REGEX": "(____){____}"}}]}]

# Load a blank model and add an EntityRuler
nlp = spacy.____("en")
ruler = nlp.____("entity_ruler")

# Add the compiled patterns to the EntityRuler
ruler.____(patterns)

# Print the tuple of entities texts and types for the given text
doc = ____(____)
print([(ent.____, ent.____) for ent in doc.____])
編輯並執行程式碼