検索条件の絞り込み
ここでは、ユーザーが一度にすべての条件を指定しなくても、段階的にフィルターを追加できるボットを作成します。
そのために、空の辞書 params を respond() 関数の外側で初期化します(前の演習のように関数の内側ではなく)。
respond() 関数は、この辞書を引数として受け取ります。
この演習はコースの一部です
Python でチャットボットを作る
演習の手順
messageとparams辞書の2つを引数として受け取り、ユーザーへの返信メッセージと更新されたparams辞書の2つを返すrespond()関数を定義してください。- 前の演習と同様に、
interpreterの.parse()メソッドを使ってmessageから"entities"を抽出してください。 find_hotels()関数を使って、paramsに一致するホテルを検索してください。respond()関数の外側でparams辞書を初期化し、回答を送信してメッセージをボットに渡しましょう。
実践的なインタラクティブ演習
このサンプルコードを完成させて、この演習に挑戦してみましょう。
# Define a respond function, taking the message and existing params as input
def ____(____, ____):
# Extract the entities
entities = ____
# Fill the dictionary with entities
for ent in entities:
params[ent["entity"]] = str(ent["value"])
# Find the hotels
results = ____
names = [r[0] for r in results]
n = min(len(results), 3)
# Return the appropriate response
return responses[n].format(*names), params
# Initialize params dictionary
params = ____
# Pass the messages to the bot
for message in ["I want an expensive hotel", "in the north of town"]:
print("USER: {}".format(message))
response, params = respond(message, params)
print("BOT: {}".format(response))