簡體   English   中英

比較用戶輸入和關鍵詞列表

[英]compare user input to list of key words

我想通過功能接受用戶輸入並將其與關鍵字列表進行比較,如果用戶輸入的任何單詞與關鍵字匹配,則滿足條件並中斷循環。 如果沒有一個單詞與關鍵字匹配,則控制台再次要求輸入。 我一直在操縱該循環,或者不管是否遇到關鍵字都讓它不斷地要求輸入,或者驗證每個輸入的單詞。 任何有關如何糾正它的建議將不勝感激。

def validated_response(user_complaint):
    valid_list = user_complaint.split()

    while True:
           if user_complaint == "stop":
                    break
           for valid in valid_list:
                    if valid.lower() not in user_complaint.lower():
                           print("Response not recognized, please try again")
                           input("Enter response: ")
                           continue

                    else:
                           print("response validated: ")
            break
        return True

此功能將繼續獲取用戶輸入,直到輸入匹配“ kwrd1”,“ kwrd2”或“ kwrd3”為止:

def get_input():
    keywords = ['kwrd1', 'kwrd2', 'kwrd3']
    user_input = None
    while True:
        user_input = input()
        if user_input in keywords:
            break
    return user_input

如果您將其與python關鍵字匹配,則有一個內置的keyword模塊:

import keyword

def get_input():
    user_input = None
    while True:
        user_input = input()
        if keyword.iskeyword(user_input):
            break
    return user_input

如果valid_list中的第一個元素不是user_complaint字符串的子字符串,則始終會到達else語句。 這意味着您總是在打破for循環並重新進入無限的while循環。 嘗試以下方法:

def validated_response(user_complaint):
    valid_list = user_complaint.split()
    if user_complaint == "stop":
        return
    inp = input("Enter response: ")
    while inp.lower() not in valid_list:
        inp = input("Enter response: ")

提供的代碼有許多問題。 該示例也沒有顯示該函數的調用方式,但是我假設您想使用包含所有要查找的關鍵字的文本來調用該函數。

第一個問題是您正在調用輸入,但未存儲其返回值,因此實際上並沒有收集用戶輸入。

其次,您正在將valid_list的各個部分與user_complaint.lower()的內容進行比較,但這意味着您正在將一個字符串與另一個字符串中的字符進行比較-而不是您想要的。

第三,您在循環內的條件的單個子句中請求新輸入,因此這將導致消息重復打印,並且用戶必須在完成所有比較之前輸入新文本。

最后,您以一種行不通的方式混合了continuebreakreturn continue告訴Python continue進行下一個循環,跳過當前循環中所有剩余的代碼。 break告訴Python退出當前塊(在這種情況下為循環)。 return告訴Python完全退出該函數並返回提供的值(如果None提供,則返回None )。

這是一個或多或少遵循您設置的結構的示例,但是所有問題都已得到糾正:

def validated_response(keywords):
    valid_list = keywords.split()

    while True:
        user_input = input('Enter response: ').lower().split()
        if user_input == ['stop']:
            return False
        for valid in valid_list:
            if valid.lower() in user_input:
                print('response validated: ')
                return True
        print('Response not recognized, please try again')


print(validated_response('trigger test'))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM