ValueError: слишком много значений для распаковки при попытке получить сообщение обратного вызова от чат-бота - PullRequest
0 голосов
/ 20 февраля 2020

Я новичок, когда дело доходит до использования python и пытается создать чат-бота, просматривая основные c методы определения функций из datacamp / others. Однако, получая эту ошибку, когда я пытаюсь вызвать одно из моих определений функций. ошибка на "ответ, фраза = match_rule (правила, сообщение)". Может ли кто-нибудь помочь мне с этим?

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")

Получена ошибка:

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

1 Ответ

0 голосов
/ 20 февраля 2020

Добро пожаловать в StackOverflow.

Ваша проблема здесь:

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

если вы позвоните, возвращаемое значение вашего match_rule(rules, message) будет:

What's stopping you from getting a good code

он возвращает одно значение, но вы пытаетесь распаковать два, кодируя:

response, phrase = match_rule(rules,message)

либо измените возвращаемое значение match_rule, чтобы вернуть два значения, либо используйте одну из переменных response или phrase, не оба.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...