首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python语音识别与聊天机器人

Python语音识别与聊天机器人
EN

Stack Overflow用户
提问于 2017-01-02 19:10:29
回答 1查看 2.7K关注 0票数 1

我目前正在建立一个个人助理机器人作为一个挑战,而我是在学校休息。目前,我很难将ChatterBotSpeechRecognition集成。当我在同一个文件中调用这两个文件时,不会出现任何错误:

代码语言:javascript
复制
import speech_recognition as sr
from chatterbot import ChatBot

def setup():
    chatbot = ChatBot(
        'Ron Obvious',
        trainer='chatterbot.trainers.ChatterBotCorpusTrainer'
    )

    # Train based on the english corpus
    chatbot.train("chatterbot.corpus.english")
    while True:
        get_response(chatbot)

def get_response(chatbot):
    # Get a response to an input statement
    speech = return_audio()
    print chatbot.get_response(speech)

def return_audio():
    r = sr.Recognizer()
    with sr.Microphone() as source:
        audio = r.listen(source)
    try:
        speech = r.recognize_google(audio)
        try:
            speech = str(speech)
            print speech
            return speech
        except TypeError:
            print "Error! Could not convert speech to string!"
    except sr.UnknownValueError:
        print "Error! Could not process that audio."
        return "Error!"
    except sr.RequestError as e:
        print "Error! No internet connection to Google Sound Recognizer."
        return "Error!"

setup()

但是,如果我将这两个文件保存在两个不同的文件中,就会得到一个AttributeError。我绕过程序崩溃,让它引发一个异常,但这个异常意味着机器人从来没有实际与用户互动。

贝娄有两个文件:听

代码语言:javascript
复制
import speech_recognition as sr
from chatterbot import ChatBot

import Messanger_Alert as MA
import Weather
import Email_Alert
import Chat
import Run


def start():
    bot = Chat.start()
    MA_client = MA.login()
    print "Hello Luke!"
    print "I am ready for your command! :D"
    while True:
        speech = str(return_audio())
        if not speech:
            print "Error! Speech returned nonetype!"
            continue
        else:
            try:
                if any(word in speech for word in ("Jason", "jason")): #Old key words: "SysGen", "Sysgen", "System", "system" - will reimpliment if needed
                    if any(word in speech for word in ("Message", "message", "Messenger", "messenger", "Facebook", "facebook")):
                        if any(word in speech for word in ("Send", "send")):
                            MA.send_message(MA_client) #now getting an attribute error.
                            print "Ready for next command!"
                        elif any(word in speech for word in ("Search Friend", "search friend", "Seach friend", "search Friend", "friend", "Friend", "friends", "Friends")):
                            MA.friend_search(MA_client)
                            print "Ready for next command!"
                        elif any(word in speech for word in ("Check", "check")):
                            MA.check_message(MA_client)
                            print "Ready for next command!"
                    elif any(word in speech for word in ("Email", "email")):
                        if any(word in speech for word in ("Personal", "personal", "Home", "home")):
                            Email_Alert.login1()
                            print "Ready for next command!"
                        elif any(word in speech for word in ("School", "school", "Dorm", "dorm", "UCSD", "ucsd")):
                            Email_Alert.login2()
                            print "Ready for next command!"
                    elif any(word in speech for word in ("Weather", "weather", "Forecast", "forecast")):
                        Weather.decide()
                    elif any(word in speech for word in ("Goodnight", "goodnight", "Bye", "bye", "Goodbye", "goodbye")):
                        print "Goodnight Luke!"
                        exit()
                    else:
                        Chat.talk(bot, speech)
                elif speech == "Error!":
                    return_audio()
                else:
                    Chat.talk(bot, speech)
            except sr.UnknownValueError:
                print "Error! Could not process that audio."
            except sr.RequestError as e:
                print "Error! No internet connection to Google Sound Recognizer."


def return_audio():
    r = sr.Recognizer()
    with sr.Microphone() as source:
        audio = r.listen(source)
    try:
        speech = r.recognize_google(audio)
        try:
            speech = str(speech)
            print speech
            return speech
        except TypeError:
            print "Error! Could not convert speech to string!"
    except sr.UnknownValueError:
        print "Error! Could not process that audio."
        return "Error!"
    except sr.RequestError as e:
        print "Error! No internet connection to Google Sound Recognizer."
        return "Error!"

聊天:

代码语言:javascript
复制
from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer
import os.path

import Listen

def start():
    file_list = ["Jason_logs.txt", "Sample1.txt"]
    chatbot = ChatBot('Jason', trainer='chatterbot.trainers.ChatterBotCorpusTrainer')
    for path in file_list:
        if os.path.exists(path) == "True":
            train_from_text(chatbot, path)
    train_bot(chatbot)

def train_from_text(chatbot, path):
    conversation = []
    with open(path, 'r') as f:
        while True:
            line1 = f.readline()
            line2 = f.readline()
            if not line2:
                break
            else:
                conversation.append(line1)
                conversation.append(line2)
    chatbot.set_trainer(ListTrainer)
    chatbot.train(conversation)

def train_bot(chatbot):
    # Train based on the english corpus
    chatbot.train("chatterbot.corpus.english")
    # Train based on english greetings corpus
    chatbot.train("chatterbot.corpus.english.greetings")
    # Train based on the english conversations corpus
    chatbot.train("chatterbot.corpus.english.conversations")

def talk(chatbot, entry):
    try:
        response = chatbot.get_response(str(entry))
        print response
        with open("Jason_logs.txt", "a") as f:
            f.write(entry)
            f.write(response)
    except TypeError:
        print "Error! Could not convert speech to string!"
    except AttributeError:
        print "Error! Speech not accepted by Jason's Chatterbot libraries."

我不完全确定为什么会这样,因为如果它们位于同一个文件中(第一个代码块),它们都可以工作。但是,为了组织目的,如果可能的话,我宁愿将这两个文件分开。

感谢您所能给出的任何想法和解决方案!

**编辑:**这里是跟踪错误(如果我在Chat中注释掉属性错误):

代码语言:javascript
复制
Traceback (most recent call last):
  File "C:/Users/lukec/PycharmProjects/Sysgen_AI/Run_File.py", line 24, in <module>
    startup()
  File "C:/Users/lukec/PycharmProjects/Sysgen_AI/Run_File.py", line 13, in startup
    voice()
  File "C:/Users/lukec/PycharmProjects/Sysgen_AI/Run_File.py", line 19, in voice
call Jason
    Listen.start()
  File "C:\Users\lukec\PycharmProjects\Sysgen_AI\Listen.py", line 47, in start
    Chat.talk(bot, speech)
  File "C:\Users\lukec\PycharmProjects\Sysgen_AI\Chat.py", line 39, in talk
    response = chatbot.get_response(str(entry))
AttributeError: 'NoneType' object has no attribute 'get_response'
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-01-02 19:29:19

Chat.start()不返回chatbot,因此隐式返回的值是None。尝试将return chatbot添加到start()的末尾。您还可以考虑创建自己的chatbot包装类,而不是使用模块和传递chatbot实例。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41432137

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档