猿问

将列表中的多个单词与字符串匹配

我想将列表中的多个单词与输入字符串匹配并返回匹配单词的列表。例如:


x = input("Enter a string?")

keywords= ["freeway", "doesn't turn on", "dropped", "got sick", "traffic jam", " car accident"]

输出:


Enter a string? there is a car accident on the freeway so that why I am late for the show. 


the list of matched words are: car accident, freeway

我研究过,有些人建议使用 any(): if any(keyword in x for keyword in keyword) 但它只返回 true 或 false。我怎样才能返回匹配的单词列表。任何人都可以帮助我吗?


侃侃无极
浏览 160回答 3
3回答

杨魅力

[i for i in keywords if i in x]编辑:这做你想要的

斯蒂芬大帝

您可以使用集合来找出用户输入的字符串与您的关键字之间匹配的字符串。检查以下代码:keywords= ["freeway", "doesn't turn on", "dropped", "got sick", "traffic jam", " car accident"]user_strings = []while True:    x = input("Enter a string?")    if x == 'exit':        break    user_strings.append(x)print ("User strings = %s" %(user_strings))print ("keywords = %s" %(keywords))print ("Matched Words = %s" %(list(set(keywords) & set(user_strings))))输出:Enter a string?"doesn't turn on"Enter a string?"freeway"Enter a string?"Hello"Enter a string?"World"Enter a string?"exit"User strings = ["doesn't turn on", 'freeway', 'Hello', 'World']keywords = ['freeway', "doesn't turn on", 'dropped', 'got sick', 'traffic jam', ' car accident']Matched Words = ['freeway', "doesn't turn on"]
随时随地看视频慕课网APP

相关分类

Python
我要回答