【问题标题】:UnboundLocalError: local variable 'command' referenced before assignmentUnboundLocalError:分配前引用的局部变量“命令”
【发布时间】:2021-07-04 18:17:52
【问题描述】:

我已尝试以下代码并显示错误!

import speech_recognition as sr
import pyttsx3
import pywhatkit
import datetime
import wikipedia
import pyjokes

listener = sr.Recognizer()
engine = pyttsx3.init()
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[1].id)


def talk(text):
    engine.say(text)
    engine.runAndWait()


def take_command():
    try:
        with sr.Microphone() as source:
            print('listening...')
            voice = listener.listen(source)
            command = listener.recognize_google(voice)
            command = command.lower()
            if 'alexa' in command:
                command = command.replace('alexa', '')
                print(command)
    except:
        pass
    return command

def run_alexa():
    command = take_command()
    print(command)
    if 'play' in command:
        song = command.replace('play', '')
        talk('playing ' + song)
        pywhatkit.playonyt(song)
    elif 'time' in command:
        time = datetime.datetime.now().strftime('%I:%M %p')
        talk('Current time is ' + time)
    elif 'who the heck is' in command:
        person = command.replace('who the heck is', '')
        info = wikipedia.summary(person, 1)
        print(info)
        talk(info)
    elif 'date' in command:
        talk('sorry, I have a headache')
    elif 'are you single' in command:
        talk('I am in a relationship with wifi')
    elif 'joke' in command:
        talk(pyjokes.get_joke())
    else:
        talk('Please say the command again.')


while True:
    run_alexa()

但它在以下模式中显示错误! 回溯(最近一次通话最后): 文件“/home/touhid/PycharmProjects/untitled1/dictionary.py”,第 60 行,在 run_alexa() 文件“/home/touhid/PycharmProjects/untitled1/dictionary.py”,第 35 行,在 run_alexa 命令 = take_command() 文件“/home/touhid/PycharmProjects/untitled1/dictionary.py”,第 31 行,在 take_command 返回命令 UnboundLocalError:分配前引用的局部变量“命令”

我该如何解决?

【问题讨论】:

    标签: python-3.x speech-recognition


    【解决方案1】:

    您在 try-except 块中遇到异常。最有可能在以下几行中

            with sr.Microphone() as source:
                print('listening...')
                voice = listener.listen(source)
                command = listener.recognize_google(voice)
    

    如果您在 try 块之前定义 command='',您将不会收到错误消息。但是,在您解决异常发生的原因之前,该程序无论如何都无法运行。

    更改如下:

    def take_command():
        try:
            command = ''
            with sr.Microphone() as source:
                print('listening...')
                voice = listener.listen(source)
                command = listener.recognize_google(voice)
                command = command.lower()
                if 'alexa' in command:
                    command = command.replace('alexa', '')
                    print(command)
        except:
            pass
        return command
    

    【讨论】:

    • 问题依然存在。如果我在答案中粘贴的行中有任何错误,则变量命令永远不会存在。由于您只是在出现异常时pass,因此您直接转到return command,您的程序不知道“命令”是什么。
    【解决方案2】:

    在 take_command() 中可以在行之前引发异常 command = listener.recognize_google(voice) 所以这就是为什么它可以是未定义的。

    像这样修复它:

    def take_command():
        command = None  # (<-- !!!)
        try:
            with sr.Microphone() as source:
                print('listening...')
                voice = listener.listen(source)
                command = listener.recognize_google(voice)
                command = command.lower()
                if 'alexa' in command:
                    command = command.replace('alexa', '')
                    print(command)
        except:
            pass
        return command
    

    【讨论】:

      【解决方案3】:

      缺少依赖包可能会导致此错误。要修复它,请尝试:

      pip install pyaudio

      如果这不起作用,请暂时注释take_command 中的tryexcept 代码部分,然后运行代码。这可能会导致其中一个依赖包出现错误,例如 speech_recognition

      检查哪个导入(模块名称)未定义,并使用pip安装。

      请注意,我在 Windows 上使用的是 python 3.6。

      【讨论】:

        猜你喜欢
        • 2017-08-10
        • 2020-01-16
        • 2019-12-05
        • 2017-09-19
        • 2020-09-26
        • 2022-01-02
        • 2019-03-22
        • 2019-01-24
        • 2021-07-01
        相关资源
        最近更新 更多