ComenzarEmpieza gratis

ELIZA II: Extracting key phrases

The really clever thing about ELIZA is the way the program appears to understand what you told it by occasionally including phrases uttered by the user in its responses.

In this exercise, you will match messages against some common patterns and extract phrases using re.search(). A dictionary called rules has already been defined, which matches the following patterns:

  • "do you think (.*)"
  • "do you remember (.*)"
  • "I want (.*)"
  • "if (.*)"

Inspect this dictionary in the Shell before starting the exercise.

Este ejercicio forma parte del curso

Building Chatbots in Python

Ver curso

Instrucciones del ejercicio

  • Iterate over the rules dictionary using its .items() method, with pattern and responses as your iterator variables.
  • Use re.search() with the pattern and message to create a match object.
  • If there is a match, use random.choice() to pick a response.
  • If '{0}' is in that response, use the match object's .group() method with index 1 to retrieve a phrase.

Ejercicio interactivo práctico

Prueba este ejercicio completando el código de muestra.

# Define match_rule()
def match_rule(rules, message):
    response, phrase = "default", None
    
    # Iterate over the rules dictionary
    for ____, ____ in ____:
        # Create a match object
        match = ____
        if match is not None:
            # Choose a random response
            response = ____
            if '{0}' in response:
                phrase = ____
    # Return the response and phrase
    return response.format(phrase)

# Test match_rule
print(match_rule(rules, "do you remember your last birthday"))
Editar y ejecutar código