ELIZA II: Extracting key phrases
ELIZA II: Extracting key phrases
_____________________________________________
Problem Statement:
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.
_____________________________________________
Problem Solution:
## Extracting key phrases
# Define match_rule()
def match_rule(rules, message):
response, phrase = "default", None
# Iterate over the rules dictionary
for pattern, responses in rules.items():
# Create a match object
match = re.search(pattern,message)
if match is not None:
# Choose a random response
response = random.choice(responses)
if '{0}' in response:
phrase = match.group(1)
# Return the response and phrase
return response, phrase
# Test match_rule
print(match_rule(rules, "do you remember your last birthday"))
_____________________________________________
Last modified: Monday, 26 December 2022, 3:06 PM