在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。
发布于 2016-07-05 17:04:59
之所以会发生这种情况,是因为ratio函数在计算比率时使用了序列的总长度,但它没有使用过滤元素因此,只要匹配块中的匹配数量产生相同的值(使用和不使用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 => 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
当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)]匹配的数量不同
当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
发布于 2021-02-22 05:44:02
您可以在对字符串进行排序之前删除字符串中的字符
def withoutJunk(input, chars):
return input.translate(str.maketrans('', '', chars))
a = withoutJunk('AA', ' ')
b = withoutJunk('A A', ' ')
difflib.SequenceMatcher(None, a, b).ratio()
# -> 1.0https://stackoverflow.com/questions/38129357
复制相似问题