虚拟助手程序:Python找不到变量

2024-04-19 18:38:01 发布

您现在位置:Python中文网/ 问答频道 /正文

基本上,该程序是一个虚拟助手,用于接收音频输入并将其转换为文本/字符串输入,这些输入将存储在变量“command”中。这样程序就可以检查“命令”中是否存在某些关键字,并返回相应的响应

(例如,如果命令为“助手,告诉我时间”,程序将输出“当前时间为下午3:40”)

代码如下:

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():
    global command
    try:
        with sr.Microphone() as source:
            print('Listening...')
            voice = listener.listen(source)
            command = listener.recognize_google(voice)
            command = command.lower()

            if 'assistant' in command:
                command = command.replace('assistant', '')
                print(command)
            return command
    except:
        pass
    finally:
        return command


def run():
    command = take_command()

    if 'play' in command:
        song = command.replace('play', '')
        talk(f'playing {song}')
        pywhatkit.playonyt(song)

    if 'time' in command:
        time = datetime.datetime.now().strftime('%I:%M %p')
        print(time)
        talk(f'Current time is {time}')

    if 'who is' in command:
        person = command.replace('who is', '')
        info = wikipedia.summary(person, 1)
        print(info)
        talk(info)

    elif 'joke' in command:
        talk(pyjokes.get_joke())
    else:
       talk('please repeat that command')


def main():
    run()


if __name__ == '__main__':
    main()

这是我收到的输出:

Listening...
Traceback (most recent call last):
  File "c:\Users\21018018\Documents\4 VSC\1 py\artificial_intelligence\alexa\main.py", line 73, in <module>
    main()
  File "c:\Users\21018018\Documents\4 VSC\1 py\artificial_intelligence\alexa\main.py", line 69, in main
    run()
  File "c:\Users\21018018\Documents\4 VSC\1 py\artificial_intelligence\alexa\main.py", line 40, in run
    command = take_command()
  File "c:\Users\21018018\Documents\4 VSC\1 py\artificial_intelligence\alexa\main.py", line 36, in take_command
    return command
NameError: name 'command' is not defined

我试过:

谢谢大家!!谢谢你抽出时间