从Python列表中查找输入字符串的所有紧密匹配项
假设我们给了一个单词,我们想找到它最接近的匹配项。不是完全匹配,而是其他单词在模式上与给定单词非常相似。为此,我们使用一个名为difflib的模块,并使用其名为get_close_matches的方法。
get_close_matches
此方法是difflib模块的一部分,为我们提供了我们指定的可能模式的匹配。下面是语法。
difflib.get_close_matches(word, possibilities, n, cutoff) word: It is the word to which we need to find the match. Possibilities: This is the patterns which will be compared for matching. n: Maximum number of close matches to return. Should be greater than 0. Cutoff: The possibilities that do not score this float value between 0 and 1 are ignored.
运行上面的代码给我们以下结果-
示例
在下面的示例中,我们只说了一个单词,还列出了需要比较的可能性或模式的列表。然后我们应用该方法以获得所需的结果。
from difflib import get_close_matches
word = 'banana'
patterns = ['ana', 'nana', 'ban', 'ran','tan']
print('matched words:',get_close_matches(word, patterns))输出结果
运行上面的代码给我们以下结果-
matched words: ['nana', 'ban', 'ana']
热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短