使用语音识别时 python 出现语法错误

I am getting syntax error in python while using Speech-recoginition

data = ""

try:
    # Uses the default API key
    # To use another API key: `r.recognize_google(audio, key="GOOGLE_SPEECH_RECOGNITION_API_KEY")`
    data = r.re[enter image description here][1]cognize_google(audio)
    print("You said: " + data)
except sr.UnknownValueError:
    print("Google Speech Recognition could not understand audio")
except sr.RequestError as e:
    print("Could not request results from Google Speech Recognition service; {0}".format(e))

    return data

我遇到了这个错误

return data

文件“”,第 13 行 return 数据 ^ 语法错误:'return' 外部函数

如果您正在寻找 return "" 如果音频无效,那么这是您最后一行的缩进错误。

更新后的代码如下所示:

def audio_convertor(audio):
    data = ""

    try:
        # Uses the default API key
        # To use another API key: `r.recognize_google(audio, key="GOOGLE_SPEECH_RECOGNITION_API_KEY")`
        data = r.re[enter image description here][1]cognize_google(audio)
        print("You said: " + data)
    except sr.UnknownValueError:
        print("Google Speech Recognition could not understand audio")
    except sr.RequestError as e:
        print("Could not request results from Google Speech Recognition service; {0}".format(e))

    return data

希望这对您有所帮助。 错误的原因可能是 return 语句的缩进不正确 w.r.t 你的方法缩进。