虚拟助手python

2024-09-27 19:25:28 发布

您现在位置:Python中文网/ 问答频道 /正文

大家好,我正在尝试开发一个虚拟助手,它将帮助我完成一些项目,因此我正在尝试获取最终项目的基础知识,但是我遇到了一个错误(UnboundLocalError:local变量'command'在赋值之前被引用),我尝试将return command改为printf(command)但是它不允许我说话,终端上会出现一条消息NONE和另一个错误(TypeError:argument'NoneType'类型不可编辑)。 那么我怎样才能不停地工作呢

代码如下:

import pyttsx3
import pywhatkit
import datetime

listener = sr.Recognizer()
engine = pyttsx3.init()

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 'skor' in command:
                command = command.replace ('skor', '')
                print(command)
    except:
        pass
    return command
def run_skor():
    command = take_command()
    print(command)
    if 'play on youtube' in command:
        song = command.replace ('play on youtube', '')
        talk('playing' + song)
        pywhatkit.playonyt(song)
    elif 'search on google' in command:
        sea = command.replace ('search on google', '')
        talk ('searching' + sea)
        pywhatkit.search(sea)
    elif 'tell me the time' in command:
        time = datetime.datetime.now().strftime('%H:%M')
        print(time)
        talk('Current time is' + time)
while True:
    run_skor()```


Tags: inimportdatetimetimeondefgoogleengine
2条回答
def takeCommand():
    r = sr.Recognizer()
    with sr.Microphone() as source:
        print("Listening...")
        audio = r.listen(source)

        try:
        print("Recognizing...")
        command = r.recognize_google(audio, language='en-in')
        print(f"User said: {command}\n")

    except Exception as e:
        print("Say that again please...")
        return "None"

    return command.lower()

您只需要在take_command()函数中进行更改。这是我的版本:

def take_command():
    try:
        with sr.Microphone() as source:
            print('listening...')
            voice = listener.listen(source)
            command = listener.recognize_google(voice)
            command = command.lower()
            if 'skor' in command:
                command = command.replace ('skor', '')
                print(command)
    except sr.UnknownValueError:
        command = ""
    return command

基本上,您可以首先更改execpt命令,更具体地说sr有一个名为UnknownValueError的内置命令。我们可以使用它来更具体地说明except命令应该在什么时候工作。然后,在except中,将命令设置为""。这将停止错误,因为当返回命令时,它仍然是一个字符串,并且仍然有效

相关问题 更多 >

    热门问题