始める無料で始める

検索条件の絞り込み

ここでは、ユーザーが一度にすべての条件を指定しなくても、段階的にフィルターを追加できるボットを作成します。

そのために、空の辞書 paramsrespond() 関数の外側で初期化します(前の演習のように関数の内側ではなく)。 respond() 関数は、この辞書を引数として受け取ります。

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

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

コースを見る

演習の手順

  • messageparams 辞書の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))
コードを編集して実行