我想使用
比较字符串
事实上,在这个例子中,
在这种情况下,它将第一个
我是否发现了一个错误,或者有另一种可能的解释可以描述这种行为?
我正在Ubuntu上使用Python 3.5.2。
difflib.SequenceMatcher
从两个字符串中提取最长公共子串。我不确定是我发现了一个bug还是我误解了find_longest_match
的文档。这是我觉得令人困惑的地方:
(https://docs.python.org/3.5/library/difflib.html#difflib.SequenceMatcher.find_longest_match)换句话说,在所有最大匹配块中,返回在a中最早开始的块,并在所有最大匹配块中,返回在a中最早开始的块中最早开始的b块。
比较字符串
X this is a test
和this is a test X
,子串X
实际上是一个最大块:它不能被扩展(即,它是包含最大的)。此外,它是文本A中第一个这样的最大块。但它肯定不是最长的公共子串。我强烈怀疑这不是find_longest_match
应该找到的。事实上,在这个例子中,
find_longest_match
确实找到了最长的公共子串:>>> l = len("X this is a test")
>>> matcher = difflib.SequenceMatcher(None, "X this is a test", "this is a test X")
>>> matcher.find_longest_match(0, l, 0, l)
Match(a=2, b=0, size=14)
然而,似乎我可以使用其他一些字符串来引发上述“查找第一个最大块”的行为(如果我缩短它们,示例会出现问题):
>>> s1 = "e-like graph visualization using a spanning tree-driven layout technique with constraints specified by layers and the ordering of groups of nodes within layers. We propose a new method of how the orde"
>>> s2 = "itree graph visualization using a spanning tree-driven layout technique with constraints speci ed by layers and the ordering of groups of nodes within layers. We propose a new method of how the drivin"
>>> matcher = difflib.SequenceMatcher(None, s1, s2)
>>> matcher.find_longest_match(1, 149, 5, 149)
Match(a=1, b=47, size=1)
在这种情况下,它将第一个
-
与s1 [1]
中的-
匹配到s2 [47]
中的-
,就是这样。 最长公共子串可能是以graph visualization using…
开头的内容。我是否发现了一个错误,或者有另一种可能的解释可以描述这种行为?
我正在Ubuntu上使用Python 3.5.2。