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

3

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

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'

我正在尝试一种方法,在匹配模式搜索和字符串1&字符串2之间寻找匹配时,如果成功,则返回true。

当我使用正则表达式库进行匹配/搜索/查找时,无法帮助我。在字符串中,我已经拥有了所有所需的单词,但不是按顺序排列的;在string2中,我有一个额外的单词,并加上了复数形式。

目前,我正在对字符串进行预处理后,将每个单词与pattern_search中的每个单词在string1&2中逐一检查,是否有任何方法可以在句子之间找到匹配项?


只是好奇,你是在尝试创建自己的抄袭检测服务吗? - Sunny Patel
哈哈哈哈,太有趣了。但是我正在尝试根据匹配的关键词为给定的字符串分类类型。 - Raady
3个回答

3
你应该好好研究 difflib 库,特别是 get_close_matches 函数,它返回与要求的单词“足够接近”的单词。请确保相应地调整您的阈值 (cutoff=)。
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_search成为一个模式列表,那么你应该循环调用match函数。

这个答案基于一个假设,即您正在尝试将pattern_searchstring1进行比较,并且另一种情况是将pattern_searchstring2进行比较,而不是使用帮助程序pattern_search来比较string1string2 - Sunny Patel
difflib所有的示例都只考虑字母(字母表)而不是单词。 - Raady
@Raady,我的解决方案是基于单词和相似单词,而不是字母。你可以在我的解决方案中的return之前添加print({word:get_close_matches(word,words,cutoff = 0.8)for word in pattern})以获取匹配单词的诊断信息。请参见我的repl示例游乐场。 - Sunny Patel

-1

试一下:

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"))

匹配/搜索/查找没有帮助,因为如果单词的顺序完全相同,它们将是正确的。在string1中,我有所有的单词,但顺序不同。 - Raady
请阅读主题,我说过我正在通过拆分和比较来做同样的事情。但是由于我的整个数据量很大,所以无法应用那种方法。你的方法会让程序在庞大的数据集上感觉卡住。 - Raady

-2
在Python中,要检查一个字符串是否包含另一个字符串,你可以尝试几件事情:
使用in。
>>> pattern_search in string
True

或者找到

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

你以新的方式回答了相同的问题! - Raady

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接