difflib.SequenceMatcher不考虑垃圾论点吗?

2024-04-19 11:26:22 发布

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

在python difflib库中,SequenceMatcher类的行为是意外的,还是我误读了假定的行为?在

为什么isjunk的论点在这个案例中似乎没有什么不同?在

difflib.SequenceMatcher(None, "AA", "A A").ratio() return 0.8

difflib.SequenceMatcher(lambda x: x in ' ', "AA", "A A").ratio() returns 0.8

我的理解是,如果省略空格,这个比率应该是1。在


Tags: lambdainnonereturn案例returns省略比率
1条回答
网友
1楼 · 发布于 2024-04-19 11:26:22

这是因为ratio函数在计算比率时使用了总序列的长度,,但它没有使用isjunk过滤元素。因此,只要匹配块中的匹配数产生相同的值(有和没有isjunk),比率度量将是相同的。

由于性能原因,我假设序列没有被isjunk过滤。

def ratio(self):   
    """Return a measure of the sequences' similarity (float in [0,1]).

    Where T is the total number of elements in both sequences, and
    M is the number of matches, this is 2.0*M / T.
    """

    matches = sum(triple[-1] for triple in self.get_matching_blocks())
    return _calculate_ratio(matches, len(self.a) + len(self.b))

self.aself.b是传递给SequenceMatcher对象的字符串(序列)(在示例中为“AA”和“AA”)。isjunk函数lambda x: x in ' '仅用于确定匹配块。您的示例非常简单,因此两个调用的结果比率和匹配块是相同的。

^{pr2}$

相同的匹配块,比率是M = 2, T = 6 => ratio = 2.0 * 2 / 6

现在考虑下面的例子

difflib.SequenceMatcher(None, "AA ", "A A").get_matching_blocks()
[Match(a=1, b=0, size=2), Match(a=3, b=3, size=0)]

difflib.SequenceMatcher(lambda x: x == ' ', "AA ", "A A").get_matching_blocks()
[Match(a=0, b=0, size=1), Match(a=1, b=2, size=1), Match(a=3, b=3, size=0)]

现在匹配块是不同的,但是比率将是相同的,因为匹配的数量仍然相等

isjunk为None时:M = 2, T = 6 => ratio = 2.0 * 2 / 6

isjunklambda x: x == ' 'M = 1 + 1, T = 6 => ratio = 2.0 * 2 / 6

最后,不同数量的匹配:

difflib.SequenceMatcher(None, "AA ", "A A ").get_matching_blocks()
[Match(a=1, b=0, size=2), Match(a=3, b=4, size=0)]

difflib.SequenceMatcher(lambda x: x == ' ', "AA ", "A A ").get_matching_blocks()
[Match(a=0, b=0, size=1), Match(a=1, b=2, size=2), Match(a=3, b=4, size=0)]

匹配的数量不同

isjunk为None时:M = 2, T = 7 => ratio = 2.0 * 2 / 7

isjunklambda x: x == ' 'M = 1 + 2, T = 6 => ratio = 2.0 * 3 / 7

相关问题 更多 >