可以使用字典运行python函数吗?

2024-09-26 22:50:28 发布

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

好的,这是我的代码:

import subprocess
import playsound
import speech_recognition as sr
from gtts import gTTS

knownCommands = {"open lunar client": subprocess.call('C:/Users/Joshua/AppData/Roaming/Microsoft/Windows/Start Menu/Programs/Lunar Client')}

def speak(text):
    tts = gTTS(text=text)
    filename = "voice.mp3"
    tts.save(filename)
    playsound.playsound(filename)

def get_audio():
    r = sr.Recognizer()
    with sr.Microphone as source:
        audio = r.listen(source)
        said = ""

        try:
            said = r.recognize_google(audio)
            print(said)
        except Exception as e:
            print("Exception: " + str(e))

        return said
speak("Hello. I am SuperAssitant 1. How can I help you today?")


text = get_audio()
if text == "open lunar client":
    subprocess.call('C:/Users/Joshua/AppData/Roaming/Microsoft/Windows/Start Menu/Programs/Lunar Client')

我想知道我是否可以运行字典中的值,在本例中是knownCommands。如果你不明白我的意思,举个例子:

  1. 我有一个以python行作为值的字典
  2. 我希望能够在不再次输入的情况下运行该行

Tags: textimportclientasopencallfilenameaudio
2条回答

是的,可以将函数作为值存储在字典中。在iPython演示:

In [1]: def hello_world():
   ...:     print("Hello World!")
   ...: 

In [2]: dictionary = {'hello': hello_world}

In [3]: dictionary['hello']
Out[3]: <function __main__.hello_world()>

In [4]: dictionary['hello']()
Hello World!

选项1:如果您知道要为每个knownCommand调用subprocess.call,只需将命令存储为字符串:

knownCommands = {'open lunar client': 'C:/Users/Joshua/AppData/Roaming/Microsoft/Windows/Start  Menu/Programs/Lunar Client'}

text = get_audio()
command = knownCommands.get(text)
if command:
  subprocess.call(command)

选项2:如果每个命令可以有不同的行为,请使用lambda:

knownCommands = {'open lunar client': lambda: subprocess.call('C:/Users/Joshua/AppData/Roaming/Microsoft/Windows/Start Menu/Programs/Lunar Client')}

text = get_audio()
command = knownCommands.get(text)
if command:
  command()

相关问题 更多 >

    热门问题