開始使用免費開始

spaCy 的 PhraseMatcher

在處理非結構化文字時,你常會有很長的清單或字典,需要在文字中掃描並比對。Matcher 的樣式是手工撰寫的,而且每個 token 都要個別設定。當你有很長的片語清單時,Matcher 就不再是最佳選擇。此時,PhraseMatcher 類別能幫忙比對大型字典。本練習中,你會練習使用 PhraseMatcher 類別,針對多個詞條,找出具有相同形狀的樣式。

en_core_web_sm 模型已載入為 nlp,可直接使用。PhraseMatcher 類別也已匯入。已提供字串 text 與清單 terms 供你使用。

本練習屬於課程

使用 spaCy 的自然語言處理

檢視課程

練習說明

  • 以帶有 attr 的方式初始化 PhraseMatcher 類別,用來比對給定 terms 的形狀。
  • 建立要加入 PhraseMatcher 物件的 patterns
  • 依這些樣式尋找比對,並列印起始與結束的 token 索引,以及在 text 中對應的比對片段。

動手互動練習

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

text = "There are only a few acceptable IP addresse: (1) 127.100.0.1, (2) 123.4.1.0."
terms = ["110.0.0.0", "101.243.0.0"]

# Initialize a PhraseMatcher class to match to shapes of given terms
matcher = ____(nlp.____, attr = ____)

# Create patterns to add to the PhraseMatcher object
patterns = [nlp.make_doc(____) for term in terms]
matcher.____("IPAddresses", patterns)

# Find matches to the given patterns and print start and end characters and matches texts
doc = ____
matches = ____
for match_id, start, end in matches:
    print("Start token: ", ____, " | End token: ", ____, "| Matched text: ", doc[____:____].text)
編輯並執行程式碼