【发布时间】: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()
难道没有更有效的方法来检查要执行的命令吗?
【问题讨论】:
-
欢迎来到 Stack Overflow!如果代码有效并且您正在寻找改进它的建议,Code Review 是合适的地方。但请先查看codereview.meta.stackexchange.com/questions/5777/…。
-
使用数据驱动的方法。创建一个字典,将输入中要搜索的单词映射到要调用的函数。然后遍历字典,匹配时调用对应的函数。
-
Python 对于
else if的方式是elif -
Python 3.10.xx 现在有一个 switch/case 块:stackoverflow.com/a/66877137/421195
标签: python