微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

小助手,while循环和脚本时长问题Python 3.9

如何解决小助手,while循环和脚本时长问题Python 3.9

你好 stachoverflow 社区, 我刚刚开始编程,我的第一个项目是一个小的虚拟助手。我从 yt 视频中获得了一些灵感和支持。无论如何,出现了一些问题:当我在 Pycharm 中启动程序并且没有给出命令(我对 alexa 这个词什么也没说)时,程序在 arounf 12 秒后崩溃。我认为这与循环有关,因为我尝试用语音命令打破循环,我的下一个问题是什么。我尝试了一些事情来用语音命令结束循环内的循环,但它不起作用。这甚至可能吗?你们有其他解决方案吗? 这是错误: 回溯(最近一次调用最后一次): 文件“C:\Users”,第 54 行,在 run_alexa() 文件“C:\Users”,第 28 行,在 run_alexa 中 命令 = take_command() 文件“C:\Users”,第 26 行,在 take_command 中 返回命令 UnboundLocalError:赋值前引用了局部变量“command”

先谢谢你! 阿德里安 (我的代码)我希望你能帮助我! [https://i.stack.imgur.com/m8Neo.png][1] [https://i.stack.imgur.com/qNTdG.png][2]

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)


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("%H:%M")
        talk("The current time is " + time)
        print(time)
    elif "who is" in command:
        person = command.replace("who is","")
        info = wikipedia.summary(person,1)  # how many lines do I want in the summary
        print(info)
        talk(info)
    elif "tell me a joke" in command:
        talk(pyjokes.get_joke())
    elif "stock" in command:
        stock_price = pywhatkit.search(command)
        talk(stock_price)
    elif "stop" in command:
        talk("alexa is going down")
    else:
        talk("Please say the command again.")


while True:
    run_alexa()

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。