我是 Python 编程的初学者。最近我决定构建一个音频助手(基本上是一个带音频的聊天机器人),但是在尝试生成输出时遇到了一个问题。我编写代码的方式是,如果用户说/要求机器人做什么,是没有为机器人定义的事情,或者如果给出了特定参数,它没有任何关于做什么的命令,那么它应该给出具体的输出。它的代码如下:
# to take input from the user:
command = input("Whatever you want to say: ")
command = command.lower()
cmd = command.split()
# below are the commands to give output after processing the input
if 'hi' in cmd:
print('hey')
elif (('how')and('are'))and('you') in cmd:
print('All good! Wbu?')
elif (('hi')and('hru')) in cmd:
print('Hey! Everyting is fine! Wbu?')
else:
print('sorry, did not understand what you meant!')
上面代码的问题在于,如果用户说:(嗨,hru?)程序只会说:嘿。这是因为我在程序中使用了 elif 语句。所以我决定将它们全部更改为 if 语句:
if 'hi' in cmd:
print('hey')
if (('how')and('are'))and('you') in cmd:
print('All good! Wbu?')
if (('hi')and('hru')) in cmd:
print('Hey! Everyting is fine! Wbu?')
else:
print('sorry, did not understand what you meant!')
它的作用是,它可以很好地打印输出,但是如果应该给出任何其他语句的输出,它会给出该语句,但也会给出 else 的输出。
然后我尝试为输出定义一个函数,如果它为真,即如果用户所说的有指定的输出,那么它应该给出输出,如果没有,那么程序应该打印异常。
def commands():
if 'hi' in cmd:
print('hey')
if (('how')and('are'))and('you') in cmd:
print('All good! Wbu?')
if (('hi')and('hru')) in cmd:
print('Hey! Everyting is fine! Wbu?')
if commands()==True:
commands()
else:
print('sorry, did not understand what you meant!')
这也是第一个,打印语句以及异常。我该如何解决这个问题?