Regex 如何在不考虑顺序的字符串中查找匹配模式?

Regex 如何在不考虑顺序的字符串中查找匹配模式?,regex,python-3.x,string,nlp,Regex,Python 3.x,String,Nlp,我正在尝试匹配两个字符串之间的模式。例如,我有 pattern_search = ['education four year'] string1 = 'It is mandatory to have at least of four years of professional education' string2 = 'need to have education four years with professional degree' 当我试图在模式搜索和string1&string2之间

我正在尝试匹配两个字符串之间的模式。例如,我有

pattern_search = ['education four year'] 
string1 = 'It is mandatory to have at least of four years of professional education'
string2 = 'need to have education four years with professional degree'
当我试图在模式搜索和string1&string2之间找到匹配项时,我正在尝试一种说真的方法

当我使用regex库时,match/search/findall对我没有帮助。在string中,我有所有需要的单词,但不按顺序排列,在string2中,我有一个额外的单词加上复数

目前,我正在分割字符串,检查模式中的每个单词,并在预处理后搜索string1和String2中的每个单词,有没有办法找到句子之间的匹配

试试看:

def have_same_words(string1, string2):
    return sorted(string1.split()) == sorted(string2.split())

print(have_same_words("It is mandatory to have at least of four years of professional education", "education four year"))

如果有帮助,请接受答案。

在Python中,要检查一个字符串是否包含另一个字符串,可以尝试以下几种方法:

用于

>>> pattern_search in string
True
或找到

>>> string1.find(pattern_search)
[returns value greater than 1 if True or -1 if False]

您应该仔细查看这个库,特别是返回“足够接近”的单词的函数,以满足可能不完全匹配的单词的需求。确保相应地调整阈值(
截止=

from difflib import get_close_matches
from re import sub

pattern_search = 'education four year'
string1 = 'It is mandatory to have at least of four years of professional education'
string2 = 'need to have education four years with professional degree'
string3 = 'We have four years of military experience'

def match(string, pattern):
  pattern = pattern.lower().split()
  words = set(sub(r"[^a-z0-9 ]", "", string.lower()).split())  # Sanitize input
  return all(get_close_matches(word, words, cutoff=0.8) for word in pattern)

print(match(string1, pattern_search))  # True
print(match(string2, pattern_search))  # True
print(match(string3, pattern_search))  # False

如果您想使
pattern\u search
成为一个模式列表,那么您可能应该循环使用
match
函数。

match/search/find没有帮助,因为如果单词的顺序正确,它们将是真的。在string1中,我有所有的单词,但顺序不同。@Raady我编辑了答案,请再次检查。如果有帮助,请接受答案。请阅读主题,我说过我正在通过拆分和比较来做同样的事情。我无法应用这些,因为我的全部数据都是巨大的。你们的方法让它感觉程序被困在了巨大数据的某个地方。你们用新的方式回答了同样的问题!只是好奇,你是在尝试创建你自己的瘟疫检查服务吗?哈哈哈,太有趣了。但是我试图根据匹配的关键字对给定字符串的类型进行分类。这个答案是基于这样的假设:您试图将
pattern\u search
string1
进行比较,而另一种情况是将
pattern\u search
string2
进行比较,非
string1
vs.
string2
和辅助搜索
pattern\u search
。difflib所有示例都只考虑字母(字母表),而不考虑单词。@Raady,我的解决方案是基于单词和类似单词,而不是字母。您可以在我的解决方案中的
返回之前添加
print({word:get_close_matches(word,words,cutoff=0.8),以获取匹配单词的诊断信息。看我的例子操场。