gpt4 book ai didi

Python字符串比较相似度

转载 作者:太空宇宙 更新时间:2023-11-03 12:41:35 24 4
gpt4 key购买 nike

我正在尝试比较两个数据列表,其中包含一些表示同一对象的自由文本。例子

List 1 ['abc LLC','xyz, LLC']
List 2 ['abc , LLC','xyz LLC']

这是一个简单的例子,但问题是可能会有很多变化,比如大小写变化或添加一些“.”。之间。是否有任何 python 包可以进行比较并给出相似性度量?

最佳答案

您可以使用 Levenshtein Distance 的实现用于非精确字符串匹配的算法,例如this one from Wikibooks .

另一种选择是,例如,在原始比较之前将所有内容折叠为小写、删除空格等——这当然取决于您的用例:

import string, unicodedata
allowed = string.letters + string.digits
def fold(s):
s = unicodedata.normalize("NFKD", unicode(s).lower()).encode("ascii", "ignore")
s = "".join(c for c in s if c in allowed)
return s

for example in ['abc LLC','xyz, LLC', 'abc , LLC','xyz LLC']:
print "%r -> %r" % (example, fold(example))

会打印

'abc LLC' -> 'abcllc'
'xyz, LLC' -> 'xyzllc'
'abc , LLC' -> 'abcllc'
'xyz LLC' -> 'xyzllc'

关于Python字符串比较相似度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10006938/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com