繁体   English   中英

如果字符串包含 python 中列表的所有单词,则匹配该字符串

[英]Matching a string if it contains all words of a list in python

我有许多长字符串,我想匹配那些包含给定列表中所有单词的字符串。

keywords=['special','dreams']
search_string1="This is something that manifests especially in dreams"
search_string2="This is something that manifests in special cases in dreams"

我只想匹配 search_string2。 到目前为止我有这段代码:

if all(x in search_text for x in keywords):
   print("matched")

问题是它也会匹配 search_string1。 显然我需要包含一些使用 \w 或 \b 的正则表达式匹配,但我不知道如何在if all语句中包含正则表达式。

谁能帮忙?

您可以使用正则表达式来做同样的事情,但我更喜欢只使用 python。

python 中的字符串类可以拆分为单词列表。 (加入可以加入一个列表到字符串)。 word in list_of_words将帮助您了解单词是否在列表中。

keywords=['special','dreams']
found = True
for word in keywords:
    if not word in search_string1.split():
        found = False

可能不是最好的主意,但我们可以检查一组是否是另一组的一部分:

keywords = ['special', 'dreams']

strs = [
  "This is something that manifests especially in dreams",
  "This is something that manifests in special cases in dreams"
]

_keywords = set(keywords)
for s in strs:
  s_set = set(s.split())
  if _keywords.issubset(s_set):
    print(f"Matched: {s}")

Axe319 的评论有效,并且最接近我最初提出的如何使用正则表达式解决问题的问题。 再次引用解决方案:

all(re.search(fr'\b{x}\b', search_text) for x in keywords)

谢谢大家!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM