模糊字符串比较以合并两个列表

时间:2014-04-23 17:01:20

标签: python list match nltk sublist

如果一个子列表与另一个子列表在特定索引上共享相似的值,那么将其扩展的最有效方法是什么?如果List1的索引0处的值类似于List2的索引0的值,我想将两个子列表合并在一起。

List1 = [['V.H. Corp','b','c'],['Meredith Brands','e','f']]
List2 = [['VH Corporation','1','2'],['Meredith','3','4']]

我知道它不会是完美的,但我需要一些足以匹配“V.H”的东西。公司'和VH公司'至少。

期望的输出:

[['V.H. Corp','b','c','VH Corporation','1','2'],
 ['Meredith Brands','e','f','Meredith','3','4']]

这是我到目前为止所做的,这是不正确的:

import nltk

def MergeSimilar(self,indice1,indice2,List1,List2):
    list2_keys = map(lambda x:x[indice2],List2)
    for i,l in enumerate(List1):
        if nltk.metrics.edit_distance(l[indice1],list2_keys) < 5:
            List1[i].extend(List2[list2_keys.index(l[indice1])]) 
    return List1

结果错误:

>>> MergeSimilar(0,0,List1,List2)
[['V.H. Corp', 'b', 'c'], ['Meredith Brands', 'e', 'f']]

1 个答案:

答案 0 :(得分:0)

最简单的方法是将两个列表中的所有字母数字字符都用小写字母表示,并检查两者是否在一起(如@ njzk2所示)。如果您正在使用大型列表(我假设您正在使用此功能),请确保您只对列表中的每个元素执行一次此操作。

这样做的一种方法:

import re

def MergeSimilar(idx1, idx2, list1, list2):
    dict2 = {re.sub(r'[\W_]+', '', l2[idx2].lower()): l2 for l2 in list2}
    for l1 in list1:
        simple1 = re.sub(r'[\W_]+', '', l1[idx1].lower())
        for simple2, l2 in dict2.items(): #use .iteritems() in python 2.x
            if simple1 in simple2 or simple2 in simple1:
                l1.extend(l2)
    return list1

使用示例:

List1 = [['V.H. Corp','b','c'],['Meredith Brands','e','f']]
List2 = [['VH Corporation','1','2'],['Meredith','3','4']]

print(MergeSimilar(0, 0, List1, List2))
#[['V.H. Corp', 'b', 'c', 'VH Corporation', '1', '2'], 
# ['Meredith Brands', 'e', 'f', 'Meredith', '3', '4']]