2016-02-28 39 views
1
key_words = ("screen", "power", "wifi") 

user_input = input("Type: ") 

if user_input in key_words: 
    print ("you should do this...") 

當任何用戶類型key_words它會工作,但如果用戶在句子中進入它的工作原理是這樣:如何從python中的用戶輸入中找到關鍵字?

Type: screen is not working 
>>> 

它應該找到關鍵字「屏幕」,並輸入yes但它只是空白。我知道我必須拆分用戶的迴應,但我如何爲最近的Python做這件事?

回答

2

這看起來很不錯any。你想遍歷你的句子,並檢查是否在該列表中存在一個單詞。如果有「ANY」匹配,則返回true:

key_words = ("screen", "power", "wifi") 

user_input = input("Type: ") 

if any(i in key_words for i in user_input.split()): 
    print("you should do this...") 

您也不需要大小寫,因爲它已經會給你一個字符串。所以我刪除了它,這是沒有必要的。

正如在評論中提到的那樣,事實上在條件語句的末尾有一個語法問題。

1

由於split()返回一個列表而不是單個值,所以您必須單獨測試每個元素(在一個循環中)。

key_words = ("screen", "power", "wifi") 
user_input = input("Type: ") 

for word in user_input.split(): 
    if word in key_words: 
    print ("you should do this...") 

如果用戶輸入多個這些關鍵字,將會打印多條消息。

N.b這是用於python3。對於python2,請改爲使用raw_input。我還刪除了input()函數中的str()

+1

如果你把''if' break',該'print'將只執行一次。 – GingerPlusPlus

-1
key_words = ("screen", "power", "wifi") 
user_input = input("Type: ") 
user_words = user_input.split() 

for word in user_words: 
    if word in key_words: 
      print("you should do this...") 
+5

有些解釋是值得歡迎的。這與[本答案](http://stackoverflow.com/a/35684588/3821804)有什麼不同,提前10分鐘發佈? – GingerPlusPlus

+0

撰寫答案需要幾分鐘的時間。因此,兩個幾乎相同的答案可以在幾分鐘內發佈(另一個不使用'user_words'變量)。 –

-1

您可以使用set交集。

if set(key_words) & set(user_input.split()): 
    print ("you should do this...") 

另一個選項

這是容易得多,不言自明。計算key_words中的每個單詞。如果這些中的任何
只是說你應該這樣做......

any_word = [ True for x in user_input.split() if x in key_words] 

''' 
user_input.split() return type is a list 
so we should check whether each word in key_words 
if so then True 
''' 


''' 
finally we check the list is empty 
''' 

if any_word : 
    print ("you should do this...") 
1

該解決方案可通過2臺之間的轉換既key_words和USER_INPUT句話一組,並找到交集實現

key_words = {"screen", "power", "wifi"} 

user_input = raw_input("Type: ") 

choice = key_words.intersection(user_input.split()) 
if choice is not None: 
    print("option selected: {0}".format(list(choice)[0])) 

輸出:

Type: screen is not working 
option selected: screen 

Type: power 
option selected: power 
相關問題