17

我有 2 个超过一百万个名称的列表,命名约定略有不同。这里的目标是匹配那些相似的记录,具有 95% 的置信度的逻辑。

我知道有些库可以利用,例如 Python 中的 FuzzyWuzzy 模块。

但是,在处理方面,将一个列表中的每个字符串与另一个进行比较似乎会占用太多资源,在这种情况下,这似乎需要 100 万次乘以另外 100 万次迭代。

对于这个问题还有其他更有效的方法吗?

更新:

所以我创建了一个桶函数并应用了一个简单的规范化删除空格、符号并将值转换为小写等......

for n in list(dftest['YM'].unique()):
    n = str(n)
    frame = dftest['Name'][dftest['YM'] == n]
    print len(frame)
    print n
    for names in tqdm(frame):
            closest = process.extractOne(names,frame)

通过使用 pythons pandas,将数据加载到按年份分组的较小存储桶中,然后使用 FuzzyWuzzy 模块process.extractOne来获得最佳匹配。

结果仍然有些令人失望。在测试期间,上面的代码用于仅包含 5000 个名称的测试数据帧,并且占用了将近一个小时。

测试数据被分割。

  • 姓名
  • 年份 出生日期 月份

我正在通过它们的 YM 在同一个存储桶中的存储桶来比较它们。

问题可能是因为我使用的 FuzzyWuzzy 模块吗?感谢任何帮助。

4

3 回答 3

18

这里有几个级别的优化可以将这个问题从 O(n^2) 转变为更小的时间复杂度。

  • 预处理:在第一遍对列表进行排序,为每个字符串创建一个输出映射,映射的键可以是标准化字符串。规范化可能包括:

    • 小写转换,
    • 没有空格,特殊字符删除,
    • 如果可能,将 unicode 转换为 ascii 等价物,使用unicodedata.normalizeunidecode模块)

    这将导致"Andrew H Smith", "andrew h. smith","ándréw h. smith"生成相同的 key "andrewhsmith",并将您的百万个名称集减少为一组较小的唯一/相似分组名称。

您可以使用此实用方法来规范化您的字符串(但不包括 unicode 部分):

def process_str_for_similarity_cmp(input_str, normalized=False, ignore_list=[]):
    """ Processes string for similarity comparisons , cleans special characters and extra whitespaces
        if normalized is True and removes the substrings which are in ignore_list)
    Args:
        input_str (str) : input string to be processed
        normalized (bool) : if True , method removes special characters and extra whitespace from string,
                            and converts to lowercase
        ignore_list (list) : the substrings which need to be removed from the input string
    Returns:
       str : returns processed string
    """
    for ignore_str in ignore_list:
        input_str = re.sub(r'{0}'.format(ignore_str), "", input_str, flags=re.IGNORECASE)

    if normalized is True:
        input_str = input_str.strip().lower()
        #clean special chars and extra whitespace
        input_str = re.sub("\W", "", input_str).strip()

    return input_str
  • 现在,如果它们的规范化键相同,则类似的字符串将已经位于同一个桶中。

  • 为了进一步比较,您只需要比较键,而不是名称。例如 andrewhsmithandrewhsmeeth,因为除了上面进行的标准化比较之外,名称的这种相似性还需要模糊字符串匹配。

  • Bucketing你真的需要比较一个 5 个字符的键和 9 个字符的键,看看是否 95% 匹配?你不可以。因此,您可以创建匹配字符串的存储桶。例如,5 个字符名称将与 4-6 个字符名称匹配,6 个字符名称与 5-7 个字符等匹配。对于大多数实际匹配而言,字符键的 n+1,n-1 个字符限制是相当好的存储桶。

  • 开始匹配:大多数名称的变体在规范化格式中将具有相同的第一个字符(例如Andrew H Smith,ándréw h. smithAndrew H. Smeeth生成键andrewhsmith, andrewhsmith, 和andrewhsmeeth。它们通常不会在第一个字符上有所不同,因此您可以对a以其他键开头的键运行匹配以 , 开头a并落在长度桶内。这将大大减少您的匹配时间。无需匹配键andrewhsmithbndrewhsmith因为很少存在带有第一个字母的名称变体。

然后您可以使用此方法(或 FuzzyWuzzy 模块)的内容来查找字符串相似度百分比,您可以排除jaro_winkler或 difflib 之一以优化您的速度和结果质量:

def find_string_similarity(first_str, second_str, normalized=False, ignore_list=[]):
    """ Calculates matching ratio between two strings
    Args:
        first_str (str) : First String
        second_str (str) : Second String
        normalized (bool) : if True ,method removes special characters and extra whitespace
                            from strings then calculates matching ratio
        ignore_list (list) : list has some characters which has to be substituted with "" in string
    Returns:
       Float Value : Returns a matching ratio between 1.0 ( most matching ) and 0.0 ( not matching )
                    using difflib's SequenceMatcher and and jellyfish's jaro_winkler algorithms with
                    equal weightage to each
    Examples:
        >>> find_string_similarity("hello world","Hello,World!",normalized=True)
        1.0
        >>> find_string_similarity("entrepreneurship","entreprenaurship")
        0.95625
        >>> find_string_similarity("Taj-Mahal","The Taj Mahal",normalized= True,ignore_list=["the","of"])
        1.0
    """
    first_str = process_str_for_similarity_cmp(first_str, normalized=normalized, ignore_list=ignore_list)
    second_str = process_str_for_similarity_cmp(second_str, normalized=normalized, ignore_list=ignore_list)
    match_ratio = (difflib.SequenceMatcher(None, first_str, second_str).ratio() + jellyfish.jaro_winkler(unicode(first_str), unicode(second_str)))/2.0
    return match_ratio
于 2016-08-16T10:26:27.140 回答
4

您必须索引或规范化字符串以避免 O(n^2) 运行。基本上,您必须将每个字符串映射到一个范式,并构建一个反向字典,其中所有单词都链接到相应的范式。

让我们考虑一下“世界”和“词”的正常形式是相同的。因此,首先构建一个反向字典,Normalized -> [word1, word2, word3],例如:

"world" <-> Normalized('world')
"word"  <-> Normalized('wrd')

to:

Normalized('world') -> ["world", "word"]

你去 - 规范化字典中具有多个值的所有项目(列表) - 都是匹配的单词。

规范化算法取决于数据,即单词。考虑其中之一:

  • 声讯
  • 变音器
  • 双变音器
  • 纽约证券交易所
  • 洞穴电话
  • 科隆注音
  • MRA 法典
于 2016-08-16T08:04:12.690 回答
3

针对fuzzywuzzy,请注意当前process.extractOne 默认为WRatio,这是迄今为止他们算法中最慢的,处理器默认为utils.full_process。如果你传入 fuzz.QRatio 作为你的得分手,它会走得更快,但根据你想要匹配的内容而没有那么强大。可能只是名字很好。我个人对 token_set_ratio 有好运,它至少比 WRatio 快一些。您还可以事先在所有选择上运行 utils.full_process(),然后使用 fuzz.ratio 作为记分器和 processor=None 运行它以跳过处理步骤。(见下文)如果你只是使用基本的比率函数,fuzzywuzzy 可能有点矫枉过正。Fwiw 我有一个 JavaScript 端口(fuzzball.js),您也可以在其中预先计算令牌集并使用它们而不是每次都重新计算。)

这不会减少比较的绝对数量,但它会有所帮助。(这可能是 BK-tree?我自己也在研究同样的情况)

还要确保安装了 python-Levenshtein,以便您使用更快的计算。

**下面的行为可能会改变,待讨论的问题等**

fuzz.ratio 不会运行完整进程,并且 token_set 和 token_sort 函数接受 full_process=False 参数,如果您不设置 Processor=None 提取函数将尝试运行完整进程。可以使用 functools 的 partial 将 fuzz.token_set_ratio 与 full_process=False 作为你的记分器,并事先在你的选择上运行 utils.full_process。

于 2017-01-03T18:32:06.397 回答