我目前正在使用python制作一个交互式系统,能够理解和回复。因此,有许多条件供机器分析和处理。例如,采用以下代码(仅供参考):
if ('goodbye') in message:
rand = ['Goodbye Sir', 'Jarvis powering off in 3, 2, 1, 0']
speekmodule.speek(rand,n,mixer)
break
if ('hello') in message or ('hi') in message:
rand = ['Wellcome to Jarvis virtual intelligence project. At your service sir.']
speekmodule.speek(rand,n,mixer)
if ('thanks') in message or ('tanks') in message or ('thank you') in message:
rand = ['You are wellcome', 'no problem']
speekmodule.speek(rand,n,mixer)
if message == ('jarvis'):
rand = ['Yes Sir?', 'What can I doo for you sir?']
speekmodule.speek(rand,n,mixer)
if ('how are you') in message or ('and you') in message or ('are you okay') in message:
rand = ['Fine thank you']
speekmodule.speek(rand,n,mixer)
if ('*') in message:
rand = ['Be polite please']
speekmodule.speek(rand,n,mixer)
if ('your name') in message:
rand = ['My name is Jarvis, at your service sir']
speekmodule.speek(rand,n,mixer)
那么,有没有一种方法可以替换所有这些if-else条件??因为会有更多的条件,这会使执行变慢。你知道吗
使用字典:
排他性的“如果”:
使用RegEx映射:
由你来决定。你知道吗
首先创建一个
dict
对象,其键是tuple
字符串,您希望在message
中匹配该字符串,并将其与Jarvis应该响应的值string
相关联。例如:现在迭代每个键
dict
,检查是否有任何子字符串是消息的一部分,如果有匹配项,则调用speekmodule.speek(rand,n,mixer)
函数,如下所示:注意:这里我假设代码中的
speekmodule.speek(value, n, mixer)
正在工作,因为您的代码中没有关于这些声明的可用信息。我刚刚用value
替换了您的rand
,因为它与代码中使用的dict
返回的str
列表相同。你知道吗相关问题 更多 >
编程相关推荐