Refining your search

Refining your search

Now you'll write a bot that allows users to add filters incrementally, just in case they don't specify all of their preferences in one message.

To do this, initialize an empty dictionary params outside of your respond() function (as opposed to inside the function, like in the previous exercise). Your respond() function will take in this dictionary as an argument.

=======================================================

Instructions

  • Define a respond() function that accepts two arguments - a message and a dictionary of params - and returns two results - the message to send to the user and the updated params dictionary.
  • Extract "entities" from the message using the .parse() method of the interpreter, exactly like you did in the previous exercise.
  • Find the hotels that match params using your find_hotels() function.
  • Initialize the params dictionary outside the respond() function and hit 'Submit Answer' to pass the messages to the bot.
=======================================================

Code

def respond(message, params):
    # Parse the message for entities
    entities = interpreter.parse(message)["entities"]
    # Fill the dictionary with entities
    for ent in entities:
        params[ent["entity"]] = str(ent["value"])
    # Find the hotels that match the params
    results = find_hotels(params)
    # Get the names of the hotels and limit to three
    names = [r[0] for r in results][:3]
    # Prepare the response
    if len(names) == 0:
        return "I'm sorry, I couldn't find any matching hotels.", params
    elif len(names) == 1:
        return "The only hotel available is " + names[0] + ".", params
    elif len(names) == 2:
        return "I found {} and {} for you.".format(names[0], names[1]), params
    else:
        names = ", ".join(names)
        return "Here are a few options: {}.".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))
Last modified: Friday, 7 July 2023, 12:13 PM