查找两个字符串的相对匹配

Find relative match of two strings

我正在编写一个函数来比较两个字符串(用例是将银行对帐单与开票时创建的原始字符串进行比较)。我很想知道原始字符串中较小的字符串 compareSting 有多少百分比(分数)。至少需要考虑 4 个连续的字符。匹配顺序无关紧要

def relStringMatch(originalString,compareString):

    smallestMatch=4

    originalString=originalString.upper()
    compareString=compareString.upper()

    stringLength=len(compareString)
    lastTest=stringLength-smallestMatch

    index=0
    totalMatch=0
    while index < lastTest:
        nbChars = smallestMatch
        found=False
        while (index+nbChars) <= stringLength:
            checkString=compareString[index:index+nbChars]
            if originalString.find(checkString) <0:
                if (nbChars==smallestMatch): nbChars=0
                nbChars-=1
                break
            else: found=True
            nbChars+=1
        if found:
            totalMatch+=nbChars
            index+=nbChars
        else: index+=1
    return totalMatch / stringLength

代码是运行嗯,举个例子:

relStringMatch("9999EidgFinanzverwaltungsteuer", "EIDG. FINANZVERWALTUNG")

打印结果:0.95 正确。

现在的问题是:有没有更优雅的方法来完成同样的任务?如果我再过几年再看这段代码,我可能再也看不懂了...

无需重新发明轮子,您可以使用许多定义明确的指标来比较字符串和评估相似性,例如Levenshtein 距离:

https://en.wikipedia.org/wiki/Levenshtein_distance

python 个实现它的库已经存在:

https://pypi.org/project/python-Levenshtein/

from Levenshtein import ratio
ratio('Hello world!', 'Holly grail!')
# 0.583333...

ratio('Brian', 'Jesus')
# 0.0