始める無料で始める

正規表現を使った意図分類 II

patterns 辞書が完成したので、次はメッセージの意図を判定する関数を定義しましょう。

この演習はコースの一部です

Python でチャットボットを作る

コースを見る

演習の手順

  • patterns 辞書の .items() メソッドを使って、intentpattern を順番に取り出します。
  • pattern.search() メソッドを使って、message にキーワードが含まれているか調べます。
  • 一致が見つかった場合は、対応する intent を返します。
  • respond() の中で match_intent() を呼び出し、引数に message を渡したら、「回答を送信」をクリックして、ボットがどのように応答するか確認しましょう。

実践的なインタラクティブ演習

このサンプルコードを完成させて、この演習に挑戦してみましょう。

# Define a function to find the intent of a message
def match_intent(message):
    matched_intent = None
    for intent, pattern in ____:
        # Check if the pattern occurs in the message 
        if ____:
            matched_intent = ____
    return matched_intent

# Define a respond function
def respond(message):
    # Call the match_intent function
    intent = ____
    # Fall back to the default response
    key = "default"
    if intent in responses:
        key = intent
    return responses[key]

# Send messages
send_message("hello!")
send_message("bye byeee")
send_message("thanks very much!")
コードを編集して実行