如何从python中的用户输入中找到关键字?
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做这件事?
这看起来很不错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...")
您也不需要大小写,因为它已经会给你一个字符串。所以我删除了它,这是没有必要的。
正如在评论中提到的那样,事实上在条件语句的末尾有一个语法问题。
由于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()
。
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...")
有些解释是值得欢迎的。这与[本答案](http://stackoverflow.com/a/35684588/3821804)有什么不同,提前10分钟发布? – GingerPlusPlus
撰写答案需要几分钟的时间。因此,两个几乎相同的答案可以在几分钟内发布(另一个不使用'user_words'变量)。 –
您可以使用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...")
该解决方案可通过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
如果你把''if' break',该'print'将只执行一次。 – GingerPlusPlus