Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/316.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用语音助手打开浏览器_Python_Browser_Voice_Assistant - Fatal编程技术网

Python 使用语音助手打开浏览器

Python 使用语音助手打开浏览器,python,browser,voice,assistant,Python,Browser,Voice,Assistant,我正在python上制作自己的语音助手 我想从中打开网站,例如,我说的是“打开谷歌”和程序打开google.com 我试图在命令中编写webbrowser.open(url),但当我启动程序时,它会在没有任何命令的情况下打开网站url 这就是我现在所拥有的: import pyttsx3 import speech_recognition as sr import sys import subprocess import webbrowser def recognize_speech_fro

我正在python上制作自己的语音助手
我想从中打开网站,例如,我说的是“打开谷歌”和程序打开google.com
我试图在命令中编写webbrowser.open(url),但当我启动程序时,它会在没有任何命令的情况下打开网站url
这就是我现在所拥有的:

import pyttsx3
import speech_recognition as sr
import sys
import subprocess
import webbrowser


def recognize_speech_from_mic(recognizer, microphone) -> dict:
    if not isinstance(recognizer, sr.Recognizer):
        raise TypeError("`recognizer` must be `Recognizer` instance")

    if not isinstance(microphone, sr.Microphone):
        raise TypeError("`microphone` must be `Microphone` instance")

    with microphone as source:
        recognizer.adjust_for_ambient_noise(source)
        audio = recognizer.listen(source)

    response = {"success": True,
                "error": None,
                "transcription": None}

    try:
        response["transcription"] = recognizer.recognize_google(audio)
    except sr.RequestError:
        response["success"] = False
        response["error"] = "API unavailable"
    except sr.UnknownValueError:
        response["error"] = "Unable to recognize speech"

    return response


my_phrases = {
# Names

              'Elsea': ["Hey there", None],
              'elsea': ["Hey there", None],
              'Elsa': ["I'm listening", None],
              'elsa': ["I'm listening", None],
              'Elsia': ["I'm here", None],
              'elsia': ["I'm here", None],
              'Chelsea': ["Go ahead", None],
              'chelsea': ["Go ahead", None],
# Main
              'hello': ['Hi!, How are you?', None],
              'what can you do': ["I can open application and that's all :)", None],
# Stop
              'stop': ['Turning off', 'exit'],
              'exit': ['Goodbye ;)', 'exit'],
              'turn off': ['One moment please...', 'exit'],
# Programs

              'open url': ['Yes,sir', webbrowser.open('google.com')],

        # Chrome
              'Chrome': ['Okay, opening Chrome', chrome],
              'open Chrome': ['Opening....', chrome],
              'chrome': ['Alright, opening Chrome', chrome],
              'open chrome': ['Yes sir', chrome],
              
              }

unknown_command_phrase = ["", None]

engine = pyttsx3.init()

en_voice_id_m = "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\Voices\Tokens\TTS_MS_EN-US_DAVID_11.0"
en_voice_id_f = "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\Voices\Tokens\TTS_MS_EN-US_ZIRA_11.0"
gb_voice_id_f = "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\Voices\Tokens\TTS_MS_EN-GB_HAZEL_11.0"

voices = engine.getProperty('voices')
engine.setProperty('voice', en_voice_id_f)
engine.setProperty('rate', 195)
while True:
    engine.runAndWait()
    
    recognizer = sr.Recognizer()
    microphone = sr.Microphone()
    print("Say something!")
    response = recognize_speech_from_mic(recognizer, microphone)
    pattern = response['transcription']  # get transcription from response dict
    say, command = my_phrases.get(pattern, unknown_command_phrase)  # retrieve response from my_phrases
    engine = pyttsx3.init()
    engine.say(say)
    if command == None:
        print(f'Looks like you said:\n{pattern}.\n')
        pass
    elif command == 'exit':
        sys.exit()
    else: 
        subprocess.check_output(command, shell=True)  # assumes you have these properly configured
        pass
如果我写webbrowser.open(url),它会在我启动程序时打开它,但我只想在我说“打开…”时打开它 我不知道怎么做
请大家帮忙

两件事:

  • 子流程。检查输出用于运行命令(程序)。但是在您的模式中有
    webbrowser.open()
    ,这是一个函数
  • 浏览器在程序启动时打开的原因是,当程序启动时,初始化词典时会立即调用函数
    webbrowser.open()

    要解决此问题:
  • 不要使用webbrowser.open。使用参数直接调用命令
    'openurl':['Yes,sir','chrome','www.google.com',
  • 在subprocess.check\u输出中使用参数
    子流程。检查输出(**命令,shell=True)
  • 两件事:

  • 子流程。检查输出用于运行命令(程序)。但是在您的模式中有
    webbrowser.open()
    ,这是一个函数
  • 浏览器在程序启动时打开的原因是,当程序启动时,初始化词典时会立即调用函数
    webbrowser.open()

    要解决此问题:
  • 不要使用webbrowser.open。使用参数直接调用命令
    'openurl':['Yes,sir','chrome','www.google.com',
  • 在subprocess.check\u输出中使用参数
    子流程。检查输出(**命令,shell=True)
  • 您可以在模式中查找“OpenURL”,拆分元素并将最后一个单词作为网页地址。我对它进行了测试,效果良好

  • 模式是你所说的字符串
  • 我们在模式中寻找“开放URL”
  • 如果patter中有一个“开放URL”,那么这意味着你说了例如“开放URL facebook”
  • 然后,我们将模式拆分,并在本例中获得最后的话语权
  • 我们在CMD6中运行“启动chrome facebook.com”。Chrome开启facebook
  • 您可以在模式中查找“OpenURL”,拆分元素并将最后一个单词作为网页地址。我对它进行了测试,效果良好

  • 模式是你所说的字符串
  • 我们在模式中寻找“开放URL”
  • 如果patter中有一个“开放URL”,那么这意味着你说了例如“开放URL facebook”
  • 然后,我们将模式拆分,并在本例中获得最后的话语权
  • 我们在CMD6中运行“启动chrome facebook.com”。Chrome开启facebook

  • 我没听懂,你能解释一下吗。模式是你所说的字符串。2.我们在模式3中寻找“开放URL”。如果patter中有一个“开放URL”,那么这意味着你说了例如“开放URL facebook”4。然后,我们分割模式,并在本例中得到最后一个字facebook 5。我们在CMD6中运行“启动chrome facebook.com”。Chrome打开FaceBook不起作用,我写了
    if command==None:print(f'看起来像你说的:\n{pattern}.\n')pass elif command==exit:sys.exit()elif'try'in str(pattern):print(f'看起来像你说的:\n{pattern}.\n')link to_page=pattern.split(''-1]command='start chrome'+link_to_page+'.com'引擎。比如('opening'+link_to_page)子进程。检查_输出(command,shell=True)否则:子进程。检查_输出(command,shell=True)#假设您已经正确配置了这些过程
    您使用的是'webbrowser.open(link_to_to_page+.com'))我没有使用“subprocess.check_output(command,shell=True)”,而是添加了完整的代码,当我说:Open URL FaceBook没有捕捉到它,你能解释一下吗?1。模式是你所说的字符串。2.我们在模式3中寻找“开放URL”。如果patter中有一个“开放URL”,那么这意味着你说了例如“开放URL facebook”4。然后,我们分割模式,并在本例中得到最后一个字facebook 5。我们在CMD6中运行“启动chrome facebook.com”。Chrome打开FaceBook不起作用,我写了
    if command==None:print(f'看起来像你说的:\n{pattern}.\n')pass elif command==exit:sys.exit()elif'try'in str(pattern):print(f'看起来像你说的:\n{pattern}.\n')link to_page=pattern.split(''-1]command='start chrome'+link_to_page+'.com'引擎。比如('opening'+link_to_page)子进程。检查_输出(command,shell=True)否则:子进程。检查_输出(command,shell=True)#假设您已经正确配置了这些过程
    您使用的是'webbrowser.open(link_to_to_page+.com'))我没有使用“subprocess.check_output(command,shell=True)”,而是添加了完整的代码,当我说:Open URL facebookIt说
    Traceback(最后一次调用):第145行,在say中,command=my_短语。get(pattern,unknown_command_短语)value错误:太多的值无法解压缩(预期为2)
    Umm。。好吧,我的错。改为:phrase_list=my_phrases.get(pattern,unknown_command_phrase)say=phrase_list[0]并调用subprocess.check_输出为:subprocess.checkoutput(phrase_list[1],phrase_list[2],shell=True)没有任何更改(Try:subprocess.checkoutput(phrase_list[1:],shell=True)我尝试了这个方法,它对meLike this有效?
    'open url':['Yes,sir','chrome','www.google.com'],phrase_list=my_phrases.get(pattern,unknown_command_phrase)subprocess.checkoutput(phrase_list[1:],shell=True)
    它说的是
    回溯(最后一次调用):第145行,比如说,command=my_phrases.get(pattern,unknown_command_phrase)value错误:太多的值无法解包(预期2)
    um..好吧,我的错。改为:短语列表=m
    import pyttsx3
    import speech_recognition as sr
    import sys
    import subprocess
    import webbrowser
    
    
    def recognize_speech_from_mic(recognizer, microphone) -> dict:
        if not isinstance(recognizer, sr.Recognizer):
            raise TypeError("`recognizer` must be `Recognizer` instance")
    
        if not isinstance(microphone, sr.Microphone):
            raise TypeError("`microphone` must be `Microphone` instance")
    
        with microphone as source:
            recognizer.adjust_for_ambient_noise(source)
            audio = recognizer.listen(source)
    
        response = {"success": True,
                    "error": None,
                    "transcription": None}
    
        try:
            response["transcription"] = recognizer.recognize_google(audio)
        except sr.RequestError:
            response["success"] = False
            response["error"] = "API unavailable"
        except sr.UnknownValueError:
            response["error"] = "Unable to recognize speech"
    
        return response
    
    
    my_phrases = {
    # Names
                  'Elsi': ["Yes?", None],
                  'elsi': ["Yes?", None],
                  'Elsea': ["Hey there", None],
                  'elsea': ["Hey there", None],
                  'Elsa': ["I'm listening", None],
                  'elsa': ["I'm listening", None],
                  'Elsia': ["I'm here", None],
                  'elsia': ["I'm here", None],
                  'Chelsea': ["Go ahead", None],
                  'chelsea': ["Go ahead", None],
                  'Hey Elsi':["What's up", None],
                  'hey elsi':["What's up", None],
    # Main
                  'hello': ['Hi!, How are you?', None],
                  'who are you': ['I am Elsi, voice assistant', None],
                  'what can you do': ["I can open application and that's all :)", None],
                  'how can I call you?': ['You can call me Elsi', None],
                  "what's your name": ['My name is Elsi', None],
    # Stop
                  'stop': ['Turning off', 'exit'],
                  'exit': ['Goodbye ;)', 'exit'],
                  'turn off': ['One moment please...', 'exit'],
    # Programs
    
                  'open URL': ['Yes,sir', 'start chrome www.google.com'],
    
            # Chrome
                #   'Chrome': ['Okay, opening Chrome', chrome],
                #   'open Chrome': ['Opening....', chrome],
                #   'Elsi open chrome': ['One moment', chrome],
                #   'chrome': ['Alright, opening Chrome', chrome],
                #   'open chrome': ['Yes sir', chrome],
                #   'Elsi open chrome': ['Okay, starting Chrome', chrome],
                  
                  }
    
    unknown_command_phrase = ["", ""]
    
    engine = pyttsx3.init()
    
    en_voice_id_m = "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\Voices\Tokens\TTS_MS_EN-US_DAVID_11.0"
    en_voice_id_f = "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\Voices\Tokens\TTS_MS_EN-US_ZIRA_11.0"
    gb_voice_id_f = "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\Voices\Tokens\TTS_MS_EN-GB_HAZEL_11.0"
    
    voices = engine.getProperty('voices')
    engine.setProperty('voice', en_voice_id_f)
    engine.setProperty('rate', 195)
    #engine.say("Hello. I'm Elsi, your voice assistant.")
    while True:
        engine.runAndWait()
        
        recognizer = sr.Recognizer()
        microphone = sr.Microphone()
        print("Say something!")
        response = recognize_speech_from_mic(recognizer, microphone)
        pattern = response['transcription']  # get transcription from response dict
        say, command = my_phrases.get(pattern, unknown_command_phrase)  # retrieve response from my_phrases
        engine = pyttsx3.init()
        engine.say(say)
        if command == None:
            print(f'Looks like you said:\n{pattern}.\n')
            pass
        elif command == 'exit':
            sys.exit()
        elif 'open URL' in str(pattern):
            print(f'Looks like you said:\n{pattern}.\n')
            link_to_page = pattern.split(' ')[-1]
            engine.say('opening ' + link_to_page)
            command = 'start chrome ' + link_to_page + '.com'
            webbrowser.open(link_to_page + '.com')
        else: 
            print(f'Looks like you said:\n{pattern}.\n')
            subprocess.check_output(command, shell=True)
            pass