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

时间:2021-04-16 21:35:12

标签: 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. 我希望无需再次输入即可运行该行。

2 个答案:

答案 0 :(得分:0)

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

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()

答案 1 :(得分:0)

是的,可以将函数作为值存储在字典中。在 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!
相关问题