バリエーションを加える
毎回同じ答えが返ってくるのは少し退屈ですよね。この演習では、応答にバリエーションを持たせます。ボットに「気分はどう?」と聞いたとき、"oh I'm great!" または "I'm very sad today" が同じ確率で返ってくるようにしましょう。
ここでは random モジュール、特に random.choice(ls) を使います。これはリスト ls からランダムに要素を1つ選ぶ関数です。
あらかじめ responses という辞書が定義されています。この辞書は、各メッセージをキーとして、対応する応答のリストをマッピングしています。
この演習はコースの一部です
Python でチャットボットを作る
実践的なインタラクティブ演習
このサンプルコードを完成させて、この演習に挑戦してみましょう。
# Import the random module
____
name = "Greg"
weather = "cloudy"
# Define a dictionary containing a list of responses for each message
responses = {
"what's your name?": [
"my name is {0}".format(name),
"they call me {0}".format(name),
"I go by {0}".format(name)
],
"what's today's weather?": [
"the weather is {0}".format(weather),
"it's {0} today".format(weather)
],
"default": ["default message"]
}
# Use random.choice() to choose a matching response
def respond(message):
# Check if the message is in the responses
if message in responses:
# Return a random matching response
bot_message = ____(____[____])
else:
# Return a random "default" response
bot_message = ____.____(____["____"])
return bot_message