Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/281.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/sharepoint/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 比较两个字符串并返回最相似的字符串_Python_Comparison - Fatal编程技术网

Python 比较两个字符串并返回最相似的字符串

Python 比较两个字符串并返回最相似的字符串,python,comparison,Python,Comparison,我必须编写一个函数,将一个字符串作为参数,并将该字符串与另外两个字符串进行比较,然后返回最相似的字符串和差异数 def func("LUMB"): lst=["JIBM", "NUNE", "NUMB"] should return: ("NUMB",1) 我试过: def f(word): lst=["JIBM", "NUNE", "NUMB"] for i in lst: d=k(word, lst) return differenc

我必须编写一个函数,将一个字符串作为参数,并将该字符串与另外两个字符串进行比较,然后返回最相似的字符串和差异数

def func("LUMB"):
    lst=["JIBM", "NUNE", "NUMB"]
should return:
("NUMB",1)
我试过:

def f(word):
    lst=["JIBM", "NUNE", "NUMB"]
    for i in lst:
        d=k(word, lst)
        return differences
        for n in d:
            print min(sum(n))
其中:

def k(word1, word2):
    L=[]
    for w in range(len(word1)):
        if word1[w] != word2[w]:
            L.append(1)
        else:
            L.append(0)
    return L

因此,如果word1=“NUMB”和word2=“LUMB”

看起来Shawn Chin提供了最好的解决方案,那么我会得到一个例如[1,0,0,0]的列表,但是如果您不能使用非内置模块,那么从
difflib
看起来可能会有帮助:

import difflib
difflib.get_close_matches("LUMB", ["JIBM", "NUNE", "NUMB"], 1)
可以使用和使用其返回值的方法获得差异数。

使用来计算:

或者,作为一种功能:

from Levenshtein import distance
from operator import itemgetter
def closest(word, lst):
    return min([(x, distance(word, x)) for x in lst], key=itemgetter(1))

print closest("NUMB", ["JIBM", "NUNE", "NUMB"])

p、 如果你想避免额外的依赖,你可以实现你自己的函数来计算距离。例如,在每个版本中提出了几个版本,各有其优缺点


但是,如果性能是一个问题,请考虑坚持定制的模块。除此之外,还有和(如果你碰巧已经使用过)。

你看过了吗?网站上的这个链接上也会有很多答案,有一篇类似的帖子。您将在这里得到一些更有价值的答案。请不要通过删除代码来破坏您的问题。@Talonmes删除后代码是否已恢复?虽然这不会返回编辑距离,但我希望它只使用标准库+1.
from Levenshtein import distance
from operator import itemgetter
def closest(word, lst):
    return min([(x, distance(word, x)) for x in lst], key=itemgetter(1))

print closest("NUMB", ["JIBM", "NUNE", "NUMB"])