赋值前引用的局部变量(语音识别python)

Local variable referenced before assignment(speech recognition python)

import speech_recognition as sr
r = sr.Recognizer()
def speaking():
    try:
        with sr.Microphone() as source:
            r.adjust_for_ambient_noise(source)
            audio = r.listen(source)
            text1 = r.recognize_google(audio)
            text = text1.lower()
    except:
        pass
    return text

text = speaking()
if text == 'hello':
    print("You said hello")

是的,代码工作正常。但是每当 speech_recognition 听到像我清除 throat/laughing/literally 任何环境噪音的声音时,我都会得到一个 error。能告诉我原因并告诉我改正的方法吗?

你的问题。

def speaking():
    try:
        with sr.Microphone() as source:
            r.adjust_for_ambient_noise(source)
            audio = r.listen(source)
            text1 = r.recognize_google(audio)
            text = text1.lower()
    except: # here its the problem
        pass
    return text # and here

代码应该如下所示

def speaking():
    try:
        with sr.Microphone() as source:
            r.adjust_for_ambient_noise(source)
            audio = r.listen(source)
            text1 = r.recognize_google(audio)
            text = text1.lower()
            # or you can return text here
            # and get rid of the below else block
            # return text
    except:
        # if you get an error then do nothing
        pass
        # you can return None
        return None
    else:
        # but if the try code worked then return text
        return text

当然你会得到“在赋值错误之前被引用”,因为在你的旧代码中,如果你得到一个错误,你什么都不做,然后你引用文本,但是如果你得到一个异常,文本就不会被定义当你正在录音。