这是因为
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.a
和self.b
是传递给SequenceMatcher对象的字符串(序列)(例如您示例中的“AA”和“A A”)。isjunk
函数lambda x:x in' '
仅用于确定匹配块。您的示例非常简单,因此两次调用的结果比率和匹配块都相同。
difflib.SequenceMatcher(None, "AA", "A A").get_matching_blocks()
[Match(a=0, b=0, size=1), Match(a=1, b=2, size=1), Match(a=2, 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=2, b=3, size=0)]
相同的匹配块,比率为: M = 2,T = 6 => 比率 = 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
当isjunk
为lambda 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)]
The number of matches is different.
当
isjunk
为 None 时:
M = 2, T = 7 => ratio = 2.0 * 2 / 7
当
isjunk
为
lambda x: x == ' '
时:
M = 1 + 2, T = 6 => ratio = 2.0 * 3 / 7