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.
This exercise is part of the course
Building Chatbots in Python
Exercise instructions
- Iterate over the
rules
dictionary using its.items()
method, withpattern
andresponses
as your iterator variables. - Use
re.search()
with thepattern
andmessage
to create amatch
object. - If there is a match, use
random.choice()
to pick aresponse
. - If
'{0}'
is in thatresponse
, use thematch
object's.group()
method with index1
to retrieve a phrase.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# 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"))