【问题标题】:Fuzzy string matching in PythonPython中的模糊字符串匹配
【发布时间】:2016-08-16 07:52:41
【问题描述】:

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

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

但是在处理方面,将 1 个列表中的每个字符串与另一个进行比较似乎会占用太多资源,在这种情况下,这似乎需要 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 模块吗?感谢任何帮助。

【问题讨论】:

  • 您可以尝试规范化名称并比较规范化的形式。这变得非常可并行化。
  • 您如何建议进行标准化?有没有我可以应用的标准方法?感谢您的反馈。
  • 这取决于命名差异的种类?举个简单的例子,匹配公司名称,我可能会去掉像 LTDINC 这样的短语,甚至可能是非字母。
  • 我猜这就是名称的难点,我们可以标准化,但这无助于减少迭代次数。
  • 您能否从您的列表中发布一些数据,这将有助于达成解决方案。例如,有哪些稍微不同的命名约定?哪两个名字被认为是 95% 匹配?

标签: python algorithm fuzzy-search fuzzywuzzy


【解决方案1】:

这里有几种可能的优化级别,可以将这个问题从 O(n^2) 降低到更小的时间复杂度。

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

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

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

您可以使用这个utlity method 来规范您的字符串(但不包括 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 字符键的 n+1,n-1 个字符限制是相当不错的存储桶。

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

然后您可以使用此method(或 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

【讨论】:

  • 你好,用分桶和标准化尝试了你的方法。这很有意义,但是仍然停留在处理时间太长的问题上。将近一个小时来处理 5000 个名字。目前使用 FuzzyWuzzy 模块,带有 process.extractOne 功能。非常感谢任何帮助。
【解决方案2】:

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

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

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

to:

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

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

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

  • Soundex
  • 变音器
  • 双重变音位
  • NYSIIS
  • Caverphone
  • 科隆拼音
  • MRA 法典

【讨论】:

  • 了解,如果我的解决方案有效,我会发布更新。基于其他信息的索引和规范化似乎是一个不错的方法。
【解决方案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。

【讨论】:

    猜你喜欢
    • 2012-02-14
    • 2014-11-02
    • 2017-08-03
    • 1970-01-01
    • 2018-05-31
    • 2021-04-19
    • 1970-01-01
    • 2015-03-26
    • 2018-04-25
    相关资源
    最近更新 更多