假设我们给了一个单词,我们想找到它最接近的匹配项。不是完全匹配,而是其他单词在模式上与给定单词非常相似。为此,我们使用一个名为difflib的模块,并使用其名为get_close_matches的方法。
get_close_matches
此方法是difflib模块的一部分,为我们提供了我们指定的可能模式的匹配。下面是语法。difflib.get_close_matches(word,possibilities,n,cutoff)
word:Itisthewordtowhichweneedtofindthematch.
Possibilities:Thisisthepatternswhichwillbecomparedformatching.
n:Maximumnumberofclosematchestoreturn.Shouldbegreaterthan0.
Cutoff:Thepossibilitiesthatdonotscorethisfloatvaluebetween0and1areignored.
运行上面的代码给我们以下结果-
示例
在下面的示例中,我们只说了一个单词,还列出了需要比较的可能性或模式的列表。然后我们应用该方法以获得所需的结果。fromdifflibimportget_close_matches
word='banana'
patterns=['ana','nana','ban','ran','tan']
print('matchedwords:',get_close_matches(word,patterns))
输出结果
运行上面的代码给我们以下结果-matchedwords:['nana','ban','ana']
如果觉得《python列表查找相同字符串_从Python列表中查找输入字符串的所有紧密匹配项》对你有帮助,请点赞、收藏,并留下你的观点哦!