我正在编写一个函数来比较两个字符串(用例是将银行对账单与开票时创建的原始字符串进行比较)。我想知道小字符串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/
相关问题 更多 >
编程相关推荐