【发布时间】: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设置为None或except子句中的其他值。