首页 > 解决方案 > 供用户在 Python 中选择输入模式的函数

问题描述

我正在尝试在 python 中做一个助手类的东西,所以基本上我想要的是它要求用户在两种输入模式之间进行选择,即文本或语音输入。

但问题是我无法将它实现到主代码中。以下是我尝试制作的示例代码:

import keyboard
import speech_recognition as sr



def takecommandti():
    print(" ")
    rt=input(">>")
    return rt.lower()

def takeCommandsi():     
        print("Listening....")
        r = sr.Recognizer()
        r.dynamic_energy_threshold=False
        r.energy_threshold=4000
        r.pause_threshold = 1
        with sr.Microphone() as source:
            r.adjust_for_ambient_noise(source)
            audio = r.listen(source)
            said=""
        try:
            print("Recognizing....")
            said = r.recognize_google(audio,language='en-in')
            print(f"You Said : {said}\n")
        except sr.UnknownValueError :
            print("could not understand audio \n ~Trying Again~")
            return takeCommandsi()
        except sr.RequestError as e:
            print("Could not request results, check your internet connection; {0}".format(e))
            return "None"
        return said.lower()


input_mode_selection_variable = 0
print("Please Select in which input Mode you want to Use :) ")
print("1.Press 't' for Text Input Mode \n2.Press 's' for Speech Input Mode ")

while True :
    if keyboard.is_pressed('t'):
        print('You have successfully Selected : Text Input Mode')
        input_mode_selection_variable=False
        break
    elif keyboard.is_pressed('s'):
        print('You have successfully Selected : Speech Input Mode')
        input_mode_selection_variable=True
        break
    
def takecommand():
    if input_mode_selection_variable == False:
        takecommandti()
    elif input_mode_selection_variable ==True:
        takeCommandsi()

我怎样才能做到这一点?

标签: pythonpython-3.xkeyboardspeech-recognition

解决方案


当您在其他脚本中使用 takecommand() 函数时,我认为 input_mode_selection_variable 不会起作用。


推荐阅读