【问题标题】:How to avoid ifs for every command? [closed]如何避免每个命令的ifs? [关闭]
【发布时间】:2021-10-11 12:19:47
【问题描述】:

我正在为自己构建一个虚拟助手,如果像这里这样的例子,要求个人的每条命令都是错误和无效的:

WAKE = 'hello'


while True:
    print("Mic ready")
    text = voice.get_audio()
    if WAKE in text:
        if "note" in text:
            voice.speak("What do you want to note?")
            print("What do you want to note?")
            text = voice.get_audio()
            Vcm.note(text)
        else if "timer" in text:
            voice.speak("How long is that timer supposed to run?")
            print("How long is that timer supposed to run?")
            text = voice.get_audio()
            Vcm.timer(text)
        else:
            voice.speak("At your service")
            print("At your service")
            text = voice.get_audio()

难道没有更有效的方法来检查要执行的命令吗?

【问题讨论】:

标签: python


【解决方案1】:

你可以将你的命令分成函数:

def note():
    #note body

def timer():
    #timer body

def default():
    #default body

然后将您的命令包装在字典中:

commands = {
    'note': lambda: note(),
    'timer': lambda: timer()
}

并分别定义默认值:

default_command = lambda: default()

然后你可以检查文本中的内容:

for word in text:
   command = commands.get(word, None)
   if command not None:
       command()
       break
else:
    default_command()

不确定这是您想要的,但如果您有很多命令,它可能会使您的代码更加稀疏。

编辑

根据Can a lambda function have a bool value of false?,lambda 表达式表现得“真实”。所以你也可以简化最后一点!

for word in text:
    command = commands.get(word, None)
    if command:
        command()
        break
else:
    default_command()

【讨论】:

  • 谢谢,我试试看!
  • 好主意,但是,由于文本是一个字符串,单词不会像“Hello”然后是“make”这样遍历每个单词,而是一个接一个地遍历每个字母:“H”, “e”、“l”等。因此,不会执行任何命令-
  • 顺便说一句,上面的代码和函数声明在不同的文件中
  • 我修复了单词问题,但是当“command()”被调用时,它告诉我我错过了“note()”的一个参数,我这样做了,但是当我更改“command( )" 到 "command(text)" 它给了我太多参数的错误
  • 我很抱歉,这个是我的,我花了 10 秒的 youtube 视频才找到解决方案!仍然感谢您的想法
【解决方案2】:
while True:
    print("Mic ready")
    text = voice.get_audio()
    if WAKE in text:
        words = text.split(" ")
        for word in words:
            command = commands.get(word)
            if command:
                command(text)
                break
        else:
            vcm.default()
    ```
commands = {
'note': lambda text: note(text)

}

【讨论】:

    猜你喜欢
    • 2021-02-26
    • 2019-10-23
    • 2016-03-31
    • 2016-07-30
    • 1970-01-01
    • 1970-01-01
    • 2017-08-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多