I am beginner when it comes to using python and trying to build a chatbot by looking up basic function definition techniques from datacamp/others. However , getting this error when i am trying to call one of my function definitions. the error is on "response, phrase = match_rule(rules,message)" . Can someone help me out with this ?
rules ={'I want (.*)': ['What would it mean if you got {0}',
'Why do you want {0}',
"What's stopping you from getting {0}"]}
import re
import random
def match_rule(rules, message):
response, phrase = "default", None
# Iterate over the rules dictionary
for pattern, responses in rules.iteritems():
# 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.format(phrase)
def replace_pronouns(message):
message = message.lower()
if 'me' in message:
# Replace 'me' with 'you'
return re.sub('me','you',message)
return message
def respond(message):
# Call match_rule
response, phrase = match_rule(rules,message)
if '{0}' in response:
# Replace the pronouns in the phrase
phrase = replace_pronouns(phrase)
# Include the phrase in the response
response = response.format(phrase)
return response
respond("I want a good code")
Error received :
ValueErrorTraceback (most recent call last)
<ipython-input-27-e6efc4eacb15> in <module>()
----> 1 print(respond("I want a good code"))
<ipython-input-21-4715e10175ce> in respond(message)
1 def respond(message):
2 # Call match_rule
----> 3 response, phrase = match_rule(rules,message)
4 if '{0}' in response:
5 # Replace the pronouns in the phrase
ValueError: too many values to unpack
Welcome to StackOverflow.
Your issue is here:
def respond(message):
# Call match_rule
print(f"{match_rule(rules,message)}")
print("----")
response, phrase = match_rule(rules,message) # line with the issue
if '{0}' in response:
# Replace the pronouns in the phrase
phrase = replace_pronouns(phrase)
# Include the phrase in the response
response = response.format(phrase)
return response
if you call that, the return value of your match_rule(rules, message)
is:
What's stopping you from getting a good code
it returns one value but you are trying to unpack two by coding:
response, phrase = match_rule(rules,message)
either change the return of match_rule
to return two values or use one of the variables response
or phrase
, not both.