python - 是否有 `difflib.get_close_matches()` 的替代方法返回索引(列表位置)而不是 str 列表?

标签 python string python-3.x similarity difflib

我想使用类似 difflib.get_close_matches 的东西但是而不是最相似的字符串,我想获得索引(即列表中的位置)。

列表的索引更加灵活,因为可以将索引关联到其他数据结构(与匹配的字符串相关)。

例如,代替:

>>> words = ['hello', 'Hallo', 'hi', 'house', 'key', 'screen', 'hallo', 'question', 'format']
>>> difflib.get_close_matches('Hello', words)
['hello', 'hallo', 'Hallo']

我愿意:

>>> difflib.get_close_matches('Hello', words)
[0, 1, 6] 

似乎不存在获得此结果的参数,是否有返回索引的 difflib.get_close_matches() 的替代方法?


我对替代方案的研究

我知道我可以使用 difflib.SequenceMatcher,然后将字符串与 ratio(或 quick_ratio)进行一对一比较。但是,恐怕这会非常低效,因为:

  1. 我将不得不创建数千个 SequenceMatcher 对象并比较它们(我希望 get_close_matches 避免使用该类):

    编辑:错误。我检查了 source code of get_close_matches ,它实际上使用了 SequenceMatcher

  2. 没有截止(我猜有一个优化避免了计算所有字符串的比率)

    编辑:部分错误。代码 get_close_matches 除了使用 real_quick_ratio, quick_ratio and ratio alltogether 外没有任何重大优化。 .在任何情况下,我都可以轻松地将优化复制到我自己的函数中。我也没有考虑到 SequenceMatcher 有设置序列的方法:set_seq1set_seq2,所以至少我不必每次都创建一个对象。

  3. 据我所知,所有 python 库都是用 C 语言编译的,这会提高性能。

    编辑:我很确定情况确实如此。该函数位于名为 cpython 的文件夹中。

    编辑:直接从 difflib 执行和复制 the function 之间存在微小差异(p 值为 0.030198)在文件 mydifflib.py 中。

    ipdb> timeit.repeat("gcm('hello', _vals)", setup="from difflib import get_close_matches as gcm; _vals=['hello', 'Hallo', 'hi', 'house', 'key', 'screen', 'hallo', 'question', 'format']", number=100000, repeat=10)
    [13.230449825001415, 13.126462900007027, 12.965455356999882, 12.955717618009658, 13.066136312991148, 12.935014379996574, 13.082025538009475, 12.943519036009093, 13.149949093989562, 12.970130036002956]
    
    ipdb> timeit.repeat("gcm('hello', _vals)", setup="from mydifflib import get_close_matches as gcm; _vals=['hello', 'Hallo', 'hi', 'house', 'key', 'screen', 'hallo', 'question', 'format']", number=100000, repeat=10)
    [13.363269686000422, 13.087718107010005, 13.112324478992377, 13.358293497993145, 13.283965317998081, 13.056695280989516, 13.021098569995956, 13.04310674899898, 13.024205000008806, 13.152750282009947]
    

尽管如此,它并没有我预期的那么糟糕,我想我会继续,除非有人知道另一个库或替代方案。

最佳答案

我拿了get_close_matches的源代码,并修改它以返回索引而不是字符串值。

# mydifflib.py
from difflib import SequenceMatcher
from heapq import nlargest as _nlargest

def get_close_matches_indexes(word, possibilities, n=3, cutoff=0.6):
    """Use SequenceMatcher to return a list of the indexes of the best 
    "good enough" matches. word is a sequence for which close matches 
    are desired (typically a string).
    possibilities is a list of sequences against which to match word
    (typically a list of strings).
    Optional arg n (default 3) is the maximum number of close matches to
    return.  n must be > 0.
    Optional arg cutoff (default 0.6) is a float in [0, 1].  Possibilities
    that don't score at least that similar to word are ignored.
    """

    if not n >  0:
        raise ValueError("n must be > 0: %r" % (n,))
    if not 0.0 <= cutoff <= 1.0:
        raise ValueError("cutoff must be in [0.0, 1.0]: %r" % (cutoff,))
    result = []
    s = SequenceMatcher()
    s.set_seq2(word)
    for idx, x in enumerate(possibilities):
        s.set_seq1(x)
        if s.real_quick_ratio() >= cutoff and \
           s.quick_ratio() >= cutoff and \
           s.ratio() >= cutoff:
            result.append((s.ratio(), idx))

    # Move the best scorers to head of list
    result = _nlargest(n, result)

    # Strip scores for the best n matches
    return [x for score, x in result]

用法

>>> from mydifflib import get_close_matches_indexes
>>> words = ['hello', 'Hallo', 'hi', 'house', 'key', 'screen', 'hallo', 'question', 'format']
>>> get_close_matches_indexes('hello', words)
[0, 1, 6] 

现在,我可以将这些索引与字符串的关联数据相关联,而无需回头搜索字符串。

关于python - 是否有 `difflib.get_close_matches()` 的替代方法返回索引(列表位置)而不是 str 列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50861237/

相关文章:

python - 使用具有完全访问权限的 Boto3 将文件上传到 AWS S3

c++ - 为什么数字类型只有一个 `to_string()`?

python - 如何拆分字符串分隔的数字

c# - 如何获得字符串宽度

python - 如何在 Scipy 中实现日志均匀分布?

python - 将新行写入文件 (Python 3)

python - Pandas - 当字符串与格式匹配时出现 "time data does not match format "错误?

python - 类函数变量

python-3.x - 在 3D 空间中使用 Python 定义向量并查找角度?

python - 按列名对 CSV 进行排序