编程语言
首页 > 编程语言> > 如何在Python中对Levenshtein距离超过80%的单词进行分组

如何在Python中对Levenshtein距离超过80%的单词进行分组

作者:互联网

假设我有一个清单: –

person_name = ['zakesh', 'oldman LLC', 'bikash', 'goldman LLC', 'zikash','rakesh']

我试图以这种方式对列表进行分组,以便两个字符串之间的Levenshtein distance最大.为了找出两个单词之间的比例,我使用的是python包fuzzywuzzy.

例子 :-

>>> from fuzzywuzzy import fuzz
>>> combined_list = ['rakesh', 'zakesh', 'bikash', 'zikash', 'goldman LLC', 'oldman LLC']
>>> fuzz.ratio('goldman LLC', 'oldman LLC')
95
>>> fuzz.ratio('rakesh', 'zakesh')
83
>>> fuzz.ratio('bikash', 'zikash')
83
>>> 

我的最终目标:

My end goal is to group the words such that Levenshtein distance between them is more than 80 percent?

我的清单应该是这样的: –

person_name = ['bikash', 'zikash', 'rakesh', 'zakesh', 'goldman LLC', 'oldman LLC'] because the distance between `bikash` and `zikash` is very high so they should be together.

码:

我试图通过排序来实现这一点,但关键功能应该是fuzz.ratio.以下代码不起作用,但我正在接近这个角度的问题.

from fuzzywuzzy import fuzz
combined_list = ['rakesh', 'zakesh', 'bikash', 'zikash', 'goldman LLC', 'oldman LLC']
combined_list.sort(key=lambda x, y: fuzz.ratio(x, y))
print combined_list

Could anyone help me to combine the words so that Levenshtein distance between them is more than 80 percent?

解决方法:

这组名称

from fuzzywuzzy import fuzz

combined_list = ['rakesh', 'zakesh', 'bikash', 'zikash', 'goldman LLC', 'oldman LLC']
combined_list.append('bakesh')
print('input names:', combined_list)

grs = list() # groups of names with distance > 80
for name in combined_list:
    for g in grs:
        if all(fuzz.ratio(name, w) > 80 for w in g):
            g.append(name)
            break
    else:
        grs.append([name, ])

print('output groups:', grs)
outlist = [el for g in grs for el in g]
print('output list:', outlist)

生产

input names: ['rakesh', 'zakesh', 'bikash', 'zikash', 'goldman LLC', 'oldman LLC', 'bakesh']
output groups: [['rakesh', 'zakesh', 'bakesh'], ['bikash', 'zikash'], ['goldman LLC', 'oldman LLC']]
output list: ['rakesh', 'zakesh', 'bakesh', 'bikash', 'zikash', 'goldman LLC', 'oldman LLC']

如您所见,名称被正确分组,但顺序可能不是您想要的.

标签:python,group-by,levenshtein-distance,fuzzy-search,fuzzy-logic
来源: https://codeday.me/bug/20190519/1135772.html