[英]How to fix Unbound Local Error in my code in Python?
你能帮我修好这条鳕鱼吗? 在我像在 30 秒后运行它之后,它显示“UnboundLocalError:分配前引用的局部变量'命令'”你能帮我解决它吗? 我尝试了许多关于如何修复此错误的教程,但我做不到。
import speech_recognition as sr
import pyttsx3
import pywhatkit
import datetime
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 'idiot' in command:
command = command.replace('idiot', '')
print(command)
except:
pass
return command
def run_idiot():
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')
print(time)
talk(time)
else:
talk('Please say the command again.')
while True:
run_idiot()
如果发生异常,您将没有command
的定义,因此返回它会导致无界本地错误。 所以你需要先声明它:
def take_command():
# declare 'command' variable outside try-except
command = ""
try:
with sr.Microphone() as source:
print('listening...')
voice = listener.listen(source)
command = listener.recognize_google(voice)
command = command.lower()
if 'idiot' in command:
command = command.replace('idiot', '')
print(command)
except:
pass
return command
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.