0

在尝试查找两个字符串之间的公共子字符串时,SequenceMatcher不会返回所有预期的公共子字符串。

s1 = '++%2F%2F+Prints+%22Hello%2C+World%22+to+the+terminal+window.%0A++++++++System.out.pr%29%3B%0A++++%7D%0A%7D%0ASample+program%0Apublic+static+voclass+id+main%28String%5B%5D+args%29+'
s2 = 'gs%29+%7B%0A++++++++%2F'
# The common substring are '+%', '%0A++++++++', '%s' and 'gs%29+'
# but 'gs%29+' is not matched.

import difflib as d

seqmatch = d.SequenceMatcher(None,s1,s2)
matches = seqmatch.get_matching_blocks()

for match in matches:
    apos, bpos, matchlen = match
    print(s1[apos:apos+matchlen])

输出:

+%
%0A++++++++
%2

s1"gs%29+" 是和之间的公共子字符串s2,但SequenceMatcher.

我错过了什么吗?

谢谢

4

1 回答 1

0

也许垃圾字符混淆了算法。isjunk我为inside添加了一个 lambda 函数SequenceMatcher()

s1 = '++%2F%2F+Prints+%22Hello%2C+World%22+to+the+terminal+window.%0A++++++++System.out.pr%29%3B%0A++++%7D%0A%7D%0ASample+program%0Apublic+static+voclass+id+main%28String%5B%5D+args%29+'
s2 = 'gs%29+%7B%0A++++++++%2F'
# The expected substring is 'gs%29+'

import difflib as d

seqmatch = d.SequenceMatcher(lambda x: x in "+", s1, s2)
matches = seqmatch.get_matching_blocks()

for match in matches:
    apos, bpos, matchlen = match
    print(s1[apos:apos+matchlen])

现在的输出是

gs%29+
于 2018-10-06T00:14:34.083 回答