簡體   English   中英

如何從用戶在python中的輸入中找到關鍵字?

[英]How do I find a keyword from user's input in python?

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

user_input = input("Type: ")

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

當用戶在 key_words 中輸入任何內容時,它會起作用,但是如果用戶在句子中輸入它,它的作用是這樣的:

Type: screen is not working
>>> 

它應該找到關鍵字“屏幕”並輸入是,但它只是空白。 我知道我必須拆分用戶的響應,但是我將如何為最近的 python 執行此操作?

這對任何人來說都是一份好工作。 您想遍歷您的句子並檢查該列表中是否存在某個單詞。 如果有“ANY”匹配,返回真:

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...")

您也不需要區分大小寫,因為它已經為您提供了一個字符串。 所以我刪除了它,這是不必要的。

正如評論中提到的,您實際上在條件語句的末尾確實存在語法問題。

由於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...")

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

注意這是針對python3的。 對於 python2,請改用raw_input 我還刪除了input()函數中的str()

解決方案可以通過將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

這是我使用的:

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...")
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...")

您可以使用設置交集。

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...")

暫無
暫無

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

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