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 exercício faz parte do curso
Building Chatbots in Python
Instruções do exercício
- Iterate over the
rulesdictionary using its.items()method, withpatternandresponsesas your iterator variables. - Use
re.search()with thepatternandmessageto create amatchobject. - If there is a match, use
random.choice()to pick aresponse. - If
'{0}'is in thatresponse, use thematchobject's.group()method with index1to retrieve a phrase.
Exercício interativo prático
Experimente este exercício completando este código de exemplo.
# 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"))