给出两个长度相同的python列表。如何返回相似值的最佳匹配?

2024-06-09 03:56:45 发布

您现在位置:Python中文网/ 问答频道 /正文

给出两个python列表,其中包含字符串(人名):

list_1 = ['J. Payne', 'George Bush', 'Billy Idol', 'M Stuart', 'Luc van den Bergen']
list_2 = ['John Payne', 'George W. Bush', 'Billy Idol', 'M. Stuart', 'Luc Bergen']

我想要一张最相似的名字的地图。在

^{pr2}$

在python中有没有一种简洁的方法来实现这一点?名单平均包含5到6个名字。有时更多,但很少。有时它只是每个列表中的一个名字,拼写可能略有不同。在


Tags: 字符串列表名字johnvanlistbillygeorge
3条回答

使用此处定义的函数:http://hetland.org/coding/python/levenshtein.py

>>> for i in list_1:
...     print i, '==>', min(list_2, key=lambda j:levenshtein(i,j))
... 
^{pr2}$

你可以利用functools.partial而不是兰姆达

>>> from functools import partial
>>> for i in list_1:
...     print i, '==>', min(list_2, key=partial(levenshtein,i))
...
^{pr2}$

下面是给定解决方案的一个变体,它还优化了 全局最小距离。它使用Munkres assignment algorithm 以确保弦对是最佳的。在

from munkres import Munkres
def match_lists(l1, l2):
    # Compute a matrix of string distances for all combinations of
    # items in l1 and l2.
    matrix = [[levenshtein(i1, i2) for i2 in l2] for i1 in l1]

    # Now figure out what the global minimum distance between the
    # pairs is.
    indexes = Munkres().compute(matrix)
    for row, col in indexes:
        yield l1[row], l2[col]

l1 = [
    'bolton',
    'manchester city',
    'manchester united',
    'wolves',
    'liverpool',
    'sunderland',
    'wigan',
    'norwich',
    'arsenal',
    'aston villa',
    'chelsea',
    'fulham',
    'newcastle utd',
    'stoke city',
    'everton',
    'tottenham',
    'blackburn',
    'west brom',
    'qpr',
    'swansea'
    ]
l2 = [
    'bolton wanderers',
    'manchester city',
    'manchester united',
    'wolverhampton',
    'liverpool',
    'norwich city',
    'sunderland',
    'wigan athletic',
    'arsenal',
    'aston villa',
    'chelsea',
    'fulham',
    'newcastle united',
    'stoke city',
    'everton',
    'tottenham hotspur',
    'blackburn rovers',
    'west bromwich',
    'queens park rangers',
    'swansea city'
    ]
for i1, i2 in match_lists(l1, l2):
    print i1, '=>', i2

对于所给出的列表,其中的差异更多地源于备选方案 拼写和昵称而不是拼写错误,这种方法比 使用levenshtein或difflib。munkres模块可以在这里找到: http://software.clapper.org/munkres/

您可以尝试difflib

import difflib

list_1 = ['J. Payne', 'George Bush', 'Billy Idol', 'M Stuart', 'Luc van den Bergen']
list_2 = ['John Payne', 'George W. Bush', 'Billy Idol', 'M. Stuart', 'Luc Bergen']

mymap = {}
for elem in list_1:
    closest = difflib.get_close_matches(elem, list_2)
    if closest:
        mymap[elem] = closest[0]

print mymap

输出:

^{pr2}$

相关问题 更多 >