2017-03-21 52 views
0

所以我正在製作一個迷你聊天機器人,如果我問任何問題,但你好,它回答「我很好」 我不是最好的在Python中,所以我可能只是失去了一些東西。爲什麼我的代碼使用不同的elif語句?

代碼:

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 
>>> 
+0

請修正您的縮進。這對Python很重要,上面的版本根本不應該運行。 – Useless

回答

6

("how", "HOW", "How" in userInput)沒有做什麼,你認爲它。

我只是創建一個tuple與3個值:

("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 strongHow are you today匹配,因爲它找到子字符串,即使show不是how且順序不同。

對於「嚴重」的句子分析,我建議您查看具有Python界面的nltk(自然語言工具包)庫。

+0

對所有人都這樣做之後,現在它向所有人表示你好 – Squidsheep

+0

你一定有一些錯誤,我會盡量提供一個完整的工作代碼。 –

+0

謝謝!它的讚賞! – Squidsheep

相關問題