開始使用免費開始

Python 中的 RegEx

以規則為基礎的資訊擷取對許多 NLP 任務都很有用。某些類型的實體(例如日期或電話號碼)具有明確的格式,不用訓練任何模型,就能用一組規則辨識。在這個練習中,你會練習使用 re 套件進行 RegEx。目標是從給定的 text 中找出電話號碼。

已經為你匯入 re 套件。你可以使用 \d 來比對代表 0 到 9 任一數字的都配字元(metacharacter)樣式。

本練習屬於課程

使用 spaCy 的自然語言處理

檢視課程

練習說明

  • 定義一個樣式,以比對 (111)-111-1111 這種形式的電話號碼。
  • 使用 re.finditer() 方法找出所有相符的樣式。
  • 對每個比對結果,印出在給定 text 中的起始與結束位置,以及相符的文字片段。

動手互動練習

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

text = "Our phone number is (425)-123-4567."

# Define a pattern to match phone numbers
pattern = r"\((____){____}\)-(____){____}-(____){____}"

# Find all the matching patterns in the text
phones = re.____(pattern, text)

# Print start and end characters and matching section of the text
for match in phones:
    start_char = match.____
    end_char = match.____
    print("Start character: ", ____, "| End character: ", ____, "| Matching text: ", text[____:____])
編輯並執行程式碼