我想用输入字符串匹配列表中的多个单词,并返回匹配单词的列表。 例如:
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(): 如果有(关键字在x中表示关键字在关键字中),但它只返回true或false。 如何返回匹配单词的列表。有人能帮我吗?你知道吗
编辑:这就是你想要的
可以使用集合找出用户输入的字符串与关键字之间的匹配字符串。你知道吗
检查以下代码:
输出:
您可以使用tride和truere库。你知道吗
这是非常多样化的,因为不需要担心检索无序的匹配(感谢
dict.fromkeys
)。您可以选择在响应中包含重复项。你知道吗解释
我对re所做的就是创建一个模式来查找
keywords
*(keys)* seperated by a
|this tells
re`中的每个字符串,以查找所有匹配的键。你知道吗re.findall按文档中说明的顺序返回匹配项:
这不考虑重复项,因此
include_duplicates
参数包含在需要它们的情况下。您可以将结果转换成一个集合来删除重复项,尽管这样会丢失顺序完整性,因此我使用collections.OrderedDict并将其转换回一个列表。你知道吗投入使用:
你可以自己试试https://repl.it/repls/AbleEssentialDribbleware。你知道吗
编辑
正如您在评论中所要求的:
要解释这条线的作用:
re.compile
-从字符串生成正则表达式模式。-see the docsjoin
接受一个字符串的iterable,并使其中一个字符串都被前面的字符串隔开。-see the docsmap
&;re.escape
您可以将此内容用于您的案例但是如果您或任何阅读此内容的人正在使用更复杂的关键字搜索,则此操作将获取每个关键字并转义re
的特殊元字符-(请参阅文档:map,re.escape)这行可以在没有
map
和re.escape
的情况下重写,并且仍然可以像这样正常工作:只知道不能包含这样的字符:
(
或*
等。。。在你的关键词里。你知道吗相关问题 更多 >
编程相关推荐