開始使用免費開始

在 spaCy 中使用延伸語法進行比對

以規則為主的資訊擷取對任何 NLP pipeline 都很關鍵。Matcher 類別允許在大括號內使用一些運算子,讓樣式更具表現力。這些運算子用於延伸比對,語意上類似於 Python 的 in、not in,以及比較運算子。在本練習中,你將使用 spaCy 的比對功能 Matcher,從一段範例文字中找出指定詞彙的匹配結果。

Matcher 類別已從 spacy.matcher 函式庫匯入。你會使用呼叫 doc 取得的範例文字 Doc 容器。本練習也提供預先載入的 spaCy 模型於 nlp

本練習屬於課程

使用 spaCy 的自然語言處理

檢視課程

練習說明

  • 使用 Matchernlp 建立一個 matcher 物件。
  • 使用 IN 運算子定義樣式,能同時比對 tiny squarestiny mouthful
  • 使用此樣式在 doc 中尋找匹配。
  • 列印每個匹配的起始與結束權杖索引,以及其文字片段。

動手互動練習

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

nlp = spacy.load("en_core_web_sm")
doc = nlp(example_text)

# Define a matcher object
matcher = Matcher(nlp.____)
# Define a pattern to match tiny squares and tiny mouthful
pattern = [{"lower": ____}, {"lower": {____: ["squares", "mouthful"]}}]

# Add the pattern to matcher object and find matches
matcher.____("CustomMatcher", [____])
matches = ____(____)

# Print out start and end token indices and the matched text span per match
for match_id, start, end in matches:
    print("Start token: ", ____, " | End token: ", ____, "| Matched text: ", doc[____:____].text)
編輯並執行程式碼