TypeError: должен быть str, а не Statement - PullRequest
0 голосов
/ 18 февраля 2020

Я работаю над чат-ботом с кодом -

from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer
from chatterbot.trainers import ChatterBotCorpusTrainer
import nltk
import numpy as np
import random
import string # to process standard python strings

from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity

import os  
language = 'en'

remove_punct_dict = dict((ord(punct), None) for punct in string.punctuation)

GREETING_INPUTS = ("hello", "hi", "greetings", "sup", "what's up","hey","hii")
GREETING_RESPONSES = ["hi", "hey", "*nods*", "hi there", "hello", "I am glad! You are talking to me"]

def greeting(sentence): 
    for word in sentence.split():
        if word.lower() in GREETING_INPUTS:
            greetinput = random.choice(GREETING_RESPONSES)
            return greetinput


def response(user_response):
    robo_response=''
    user_response = str(user_response)
    robo_response = robo_response+return_response
    return robo_response

flag=True

my_bot = ChatBot(name='PyBot', read_only=True,logic_adapters=['chatterbot.logic.MathematicalEvaluation','chatterbot.logic.BestMatch'])
small_talk = ['hi there!',
              'hi!',
              'how do you do?',
              'how are you?',
              'i\'m cool.',
              'fine, you?',
              'always cool.',
              'i\'m ok',
              'glad to hear that.',
              'i\'m fine',
              'glad to hear that.',
              'i feel awesome',
              'excellent, glad to hear that.',
              'not so good',
              'sorry to hear that.',
              'what\'s your name?',
              'i\'m pybot. ask me a math question, please.']

math_talk_1 = ['pythagorean theorem',
           'a squared plus b squared equals c squared.']

math_talk_2 = ['law of cosines',
           'c**2 = a**2 + b**2 - 2 * a * b * cos(gamma)']


list_trainer = ListTrainer(my_bot)

for item in (small_talk, math_talk_1, math_talk_2):
    list_trainer.train(item)

corpus_trainer = ChatterBotCorpusTrainer(my_bot)
corpus_trainer.train('chatterbot.corpus.english')


openremark = "ROBO: My name is Robo. I will answer your queries about Chatbots. If you want to exit, type Bye!"

print("ROBO: My name is Robo. I will answer your queries about Chatbots. If you want to exit, type Bye!")

while(flag==True):
    user_response = input()
    user_response=user_response.lower()
    if(user_response!='bye'):
        if(user_response=='thanks' or user_response=='thank you' ):
            flag=False
            print("ROBO: You are welcome..")
        else:
            if(greeting(user_response)!=None):
                print("ROBO: "+greeting(user_response))
            else:
                print("ROBO: ",end="")
                print("func call user_response")
                print(user_response)
                print("end")
                user_response = str(user_response)
                print(response(user_response))
    else:
        flag=False

        offremark2 = "Bye! take care"
        print("ROBO: Bye! take care..")

При запуске команда не работает нормально -

ROBO: My name is Robo. I will answer your queries about Chatbots. If you want to exit, type Bye!
hi
ROBO: hi there
gaurav
ROBO: func call user_response
gaurav
end
user_response
gaurav
type
<class 'str'>
end
dummy check
you are busy
dummy end
user_response
gaurav
Traceback (most recent call last):
  File "chatbot-new-1.py", line 118, in <module>
    print(response(user_response))
  File "chatbot-new-1.py", line 46, in response
    robo_response = robo_response+return_response
TypeError: must be str, not Statement

Работает нормально для приветствия и * 1007 Сообщение * BYE , но когда оно должно работать с CHATTERBOT и CHATTERBOT_CORPUS, выдает ошибку.

Traceback (most recent call last):
  File "chatbot-new-1.py", line 118, in <module>
    print(response(user_response))
  File "chatbot-new-1.py", line 46, in response
    robo_response = robo_response+return_response
TypeError: must be str, not Statement

TypeError: должно быть str, а не Statement

Я даже пытался сначала создать строку user_response, а также с помощью для l oop, чтобы он работал для каждого отдельного элемента, но он поворачивался до того же сообщения. Я не могу устранить ошибку и не получил ответа на тот же или похожий вопрос.

1 Ответ

1 голос
/ 18 февраля 2020

Что такое return_response? Не похоже, что он определен.

Может быть, заменить это:

robo_response = robo_response+return_response

на это:

robo_response = robo_response+user_response
...