正規表現を使った意図分類 II
patterns 辞書が完成したので、次はメッセージの意図を判定する関数を定義しましょう。
この演習はコースの一部です
Python でチャットボットを作る
演習の手順
patterns辞書の.items()メソッドを使って、intentとpatternを順番に取り出します。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!")