为什么我的代码使用不同的elif语句?

时间:2017-03-21 13:31:50

标签: python

所以我正在制作一个迷你谈话机器人,如果我问什么,除了你好,它回答"我很好" 我在python中不是最好的,所以我可能只是遗漏了一些东西。

代码:

print("Hello, I am Squeep Bot, my current purpose is to have meaningless conversations with you, please speak to me formally, I can not understand other ways of saying things")
while True:
    userInput = input(">>> ")
    if userInput in ["hi", "HI", "Hi", "hello", "HELLO", "Hello"]:
        print("Hello")

    elif ("how", "HOW", "How" in userInput)and("are", "ARE", "Are" in userInput)and("you", "YOU", "You" in userInput):
        print ("I'm Ok")

    elif ("whats", "WHATS", "Whats", "what's", "WHAT'S", "What's" in userInput)and("favorite", "FAVORITE", "Favorite" in userInput)and("colour", "COLOUR", "Colour" in userInput):   
        print ("I like Green")

    elif ("what", "WHAT", "What" in userInput)and("is", "IS", "Is" in userInput)and("favorite", "FAVORITE", "Favorite" in userInput)and("colour", "COLOUR", "Colour" in userInput):   
        print ("I like Green")

    else:
        print("I did not understand what you said")

编译器:

Hello, I am Squeep Bot, my current purpose is to have meaningless conversations with you, please speak to me formally, I can not understand other ways of saying things
>>> hi
Hello
>>> how are you
I'm Ok
>>> whats your favorite colour
I'm Ok
>>> fafasfdf
I'm Ok
>>> 

1 个答案:

答案 0 :(得分:6)

("how", "HOW", "How" in userInput)并没有按照您的想法行事。

我只创建一个包含3个值的tuple

("how", "HOW", False)(或True)但元组是" truthy"它总是进入第一个if

您可以使用or展开,但在这种情况下,最好的办法是:

if "how" in userInput.lower() ...

因此所有外壳都得到了处理。

要处理多重匹配,最好的方法是实际使用all

ui_lower = userInput.lower()  # only perform `lower` once
if all(x in ui_lower for x in ("how","are","you")):

如果所有子字符串都在True(小写),则返回userInput

由于您似乎无法将此修改为您的代码,因此这是一个没有交互式输入的简化版本:

def analyse(user_input):
    ui_lower = user_input.lower()
    if ui_lower in ["hi", "hello"]:
        r = "Hello"
    elif all(x in ui_lower for x in ("how","are","you")):
        r = "I'm Ok"
    elif all(x in ui_lower for x in ("what","favorite","color")):
        r = "I like Green"
    else:
        r = "I'm unable to comply"
    return r

for s in ("what's your favorite color","show you are strong","hello","Drop dead"):
    print("Q: {}".format(s))
    print("A: {}".format(analyse(s)))

输出:

Q: what's your favorite color
A: I like Green
Q: How are you today?
A: I'm Ok
Q: hello
A: Hello
Q: Drop dead
A: I'm unable to comply

请注意,代码有其缺陷:它会找到子字符串,因此show you are strong匹配How are you today,因为它会找到子字符串,即使show不是how并且顺序不同。

对于"认真的"句子分析,我建议您查看具有python接口的nltk(自然语言工具包)库。