簡體   English   中英

如何修復 UnboundLocalError:分配前引用的局部變量“命令”

[英]How do i fix UnboundLocalError: local variable 'command' referenced before assignment

我正在嘗試制作一個虛擬助手,剩下的唯一問題就是這個。 我嘗試了 google 和 reddit,但我沒有得到任何答案。 我不知道如何解決它,但這里是代碼:

我輸入這個是因為堆棧溢出不會讓我發帖,除非我有更多的文字,所以這是我的人生故事。 上周在學校里我們做了一個實驗,我們必須喝 5 升水,然后在寒冷的天氣里用大麥和衣服等 10 分鍾。 我們必須看看站在寒冷中是否會讓我們比在里面更想小便。 理論是血葉會收縮,沒有水的空間,所以我們會把它尿出來。 直到下節課才開始小便,然后每個人每 10 分鍾去一次洗手間。

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)# 0 is male, 1 is female
engine.say('Booting Lora system')
engine.runAndWait()

def talk(text):
    engine.say(text)
    engine.runAndWait()

def take_command():
    try:
        with sr.Microphone() as source:
            voice = listener.listen(source)
            command = listener.recognize_google(voice)
            command = command.lower()
    except:
        pass
    return command


def run_lora():
    command = take_command()
    if 'play' in command:
        song = command.replace('play', '')
        talk('playing ' + song)
        pywhatkit.playonyt(song)
    elif 'time' in command:
        time = datetime.datetime.now().strftime('%H:%M')
        talk('Current time is ' + time)
    elif 'who' in command:
        question = command
        info = wikipedia.summary(question, 3)
        talk(info)
    elif 'tell' in command and 'joke' in command:
        talk(pyjokes.get_joke())
    else:
        talk('Sorry I did not understand')

while True:
    run_lora()

因為你在run_lora中定義了command它是一個私有變量,你只需要添加global command


def take_command():

    global command    # <---- Over Here #############

    try:
        with sr.Microphone() as source:
            voice = listener.listen(source)
            command = listener.recognize_google(voice)
            command = command.lower()
    except:
        pass
    return command

take_command() function 中將 word command更改為cmnd 您的命令變量在實際聲明之前被引用


def take_command():
    try:
        with sr.Microphone() as source:
            voice = listener.listen(source)
            cmnd = listener.recognize_google(voice)
            cmnd = cmnd.lower()
    except:
        pass
    return cmnd

我認為我的問題是我需要 pyadio 但 pyaudio 版本對於 python 3.8 來說太舊了

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM