首页 > 解决方案 > AttributeError:“ChatBot”对象没有属性“set_trainer”

问题描述

PS C:\Users\asus\Downloads\chatbot> python app.py
[nltk_data] Downloading package stopwords to
[nltk_data]     C:\Users\asus\AppData\Roaming\nltk_data...
[nltk_data]   Unzipping corpora\stopwords.zip.
[nltk_data] Downloading package wordnet to
[nltk_data]     C:\Users\asus\AppData\Roaming\nltk_data...
[nltk_data]   Unzipping corpora\wordnet.zip.
[nltk_data] Downloading package averaged_perceptron_tagger to
[nltk_data]     C:\Users\asus\AppData\Roaming\nltk_data...
[nltk_data]   Unzipping taggers\averaged_perceptron_tagger.zip.
Traceback (most recent call last):
  File "app.py", line 8, in <module>
    bot.set_trainer(ListTrainer)

我已经安装了 chatterbot 并在尝试在烧瓶中运行它时出现以下错误。我使用 python 3.7 64 位。找不到答案。我对python很陌生,请帮帮我这是代码

from flask import Flask, render_template, request
from chatterbot import ChatBot
from chatterbot.trainers import ChatterBotCorpusTrainer
from chatterbot.trainers import ListTrainer

app = Flask(__name__)
bot = ChatBot("Candice")
bot.set_trainer(ListTrainer)
bot.set_trainer(ChatterBotCorpusTrainer)
bot.train("chatterbot.corpus.english")

@app.route("/")
def home():    
    return render_template("home.html") 
@app.route("/get")
def get_bot_response():    
    userText = request.args.get('msg')    
    return str(bot.get_response(userText)) 
if __name__ == "__main__":    
    app.run()

标签: python-3.xflaskchatbotattributeerrorchatterbot

解决方案


在我重新安排 set_trainer 语句的放置之前,我遇到了这个问题,如下面的代码所示:

from chatterbot import ChatBot
from chatterbot.trainers import ChatterBotCorpusTrainer

def bot(title, read_only = True):    # , don't learn from exchanges (responses exist)
    Bot = ChatBot(title,
                   #filters=["chatterbot.filters.RepetitiveResponseFilter"],
                   logic_adapters=[{                       
                       'import_path': 'chatterbot.logic.BestMatch',
                       "statement_comparision_function": "chatterbot.comparisions.levenshtein_distance",
                       "response_selection_method": "chatterbot.response_selection.get_first_response"
                       }])
    print('Training corpus',title)
    trainer=ChatterBotCorpusTrainer(Bot)
    trainer.train("chatterbot.corpus.english." + title)     
    return Bot                                         # trained instance

bots = {}
# check what corpora available and traina a bot for each one
for item in os.listdir('C:/Python/Python38/lib/site-packages/chatterbot_corpus/data/english/'):
    corpus = item.split('.')        # of the form 'item.yml'
    name = corpus[0]
    bots[name]= bot(name)  # add bot instance to dictionary of available bots
                                                        
def exchange(input):  # let's get a response to our input
    # try suggested corpora to find best fit. If first corpus < theshold, try another.
    # neeed to avoid random responses confidence 0
    bot = bots[context]
    response = bot.get_response(input)

推荐阅读