从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 新婚快乐所有祝福语简短
18 新人结婚简短祝福语大全