有没有一种方法可以对字符串中的单词进行模糊字符串匹配



我想对字符串和单词进行模糊匹配。

目标字符串可能类似。"你好,我今天要去看电影">
我要搜索的单词在哪里
"今天的电影";。

这有望回归";今天的电影";作为搜索结果。

我用过这种方法,但似乎只对一个词有效。

import difflib
def matches(large_string, query_string, threshold):
words = large_string.split()
matched_words = []
for word in words:
s = difflib.SequenceMatcher(None, word, query_string)
match = ''.join(word[i:i+n] for i, j, n in s.get_matching_blocks() if n)
if len(match) / float(len(query_string)) >= threshold:
matched_words.append(match)
return matched_words
large_string = "Hello, I am going to watch a film today"
query_string = "film"
print(list(matches(large_string, query_string, 0.8)))

这只适用于一个单词,并且在几乎没有噪音的情况下返回。

有什么方法可以对单词进行这种模糊匹配吗?

您正在考虑的功能称为"查询建议";它确实依赖于拼写检查,但它依赖于由搜索引擎查询日志构建的马尔可夫链。

话虽如此,您使用的方法与本答案中描述的方法类似:https://stackoverflow.com/a/58166648/140837

您可以简单地使用Fuzysearch,请参阅下面的示例;

from fuzzysearch import find_near_matches
text_string = "Hello, I am going to watch a film today."
matches = find_near_matches('flim toda', text_string, max_l_dist=2)
print([my_string[m.start:m.end] for m in matches])

这将为您提供所需的输出。

['film toda']

请注意,您可以根据要容忍的程度为max_l_dist参数给定一个值。

最新更新