我是Python编程的初学者。最近,我决定构建一个音频助手(基本上是一个带有音频的聊天机器人),但在尝试生成输出时遇到了一个问题。我编写代码的方式是,如果用户说/要求bot做的事情,是bot没有定义的事情,或者如果给出了特定参数,它没有任何关于该做什么的命令,那么它应该给出一个特定的输出。其代码如下:
# 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!')
这样做的目的是,它很好地打印输出,但是如果任何其他语句的输出应该被给出,它给出了该语句,但也给出了其他语句的输出
然后我尝试为输出定义一个函数,如果它是真的,即如果用户所说的有指定的输出,那么它应该给出输出,如果没有,那么程序应该打印异常
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!')
这也是第一个,打印语句和异常。我如何解决这个问题
尽管在英语(和其他人类语言)中,说这样的话很常见:
…这不是布尔逻辑的工作原理
您实际编写的内容的解析更像这样:
类似于}, I think )
('hi' and 'hru')
的东西会给你一个无用的结果(^{您需要的是:
要完成此操作,请按如下方式重写您的条件:
相关问题 更多 >
编程相关推荐