我正在尝试从本教程https://www.youtube.com/watch?v=AWvsXxDtEkU构建一个类似于 Alexa 的 Ai 助手。所以,我收到了这个错误,我似乎无法调试它:
line 31, in take_command : return command : UnboundLocalError: local variable 'command' referenced before assignment
我知道这个问题已经被问了很多次,但我似乎无法理解解决方案,我已经阅读了很多关于未绑定错误的文章我知道这是全局和本地范围的问题,但同样的事情我不能正确理解那些...
这是我的代码:
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()
我希望你能帮我解决这个烂摊子......谢谢