【问题标题】:Getting the below error: please help: UnboundLocalError: local variable 'command' referenced before assignment收到以下错误:请帮助:UnboundLocalError: local variable 'command' referenced before assignment
【发布时间】:2021-05-11 18:35:13
【问题描述】:

在 python 中编译代码时出现以下错误。 我怎样才能摆脱这个错误。请帮忙

错误信息:

    Traceback (most recent call last):
  File "C:\Users\Sohini\PycharmProjects\myownvirtualassistant\original code.py", line 70, in <module>
    run_alexa()
  File "C:\Users\Sohini\PycharmProjects\myownvirtualassistant\original code.py", line 43, in run_alexa
    command = take_command()
  File "C:\Users\Sohini\PycharmProjects\myownvirtualassistant\original code.py", line 37, in take_command
    return command

原代码:

listener = sr.Recognizer()
engine = pyttsx3.init()
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[0].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()

UnboundLocalError: local variable 'command' referenced before assignment"

在 python 中编译代码时出现以下错误。 我怎样才能摆脱这个错误。请帮忙

这是在 Python 中创建 VA 的代码。

【问题讨论】:

  • def take_command(): 中存在command 从未定义的可能性。您已在 try 块中定义它,但如果失败,command 可能未定义。
  • 扩展上一条评论。调用sr.microphone() 时可能会出错。您应该将command 设置为Noneexcept 子句中的其他值。

标签: python command


【解决方案1】:

当分配command=take_command() 时,它应该是command=take_command

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-02-11
    • 2017-08-08
    • 2018-01-22
    • 1970-01-01
    • 2019-07-11
    • 2023-02-13
    • 2021-12-17
    • 2014-05-09
    相关资源
    最近更新 更多