我试图使用Python的SequenceMatcher
在两个字符串之间寻找匹配块。字符串是"ABCDPQRUVWXYZ"
和"PQRABCDUVWXYZ"
。但是,当我应用get_matching_blocks()
时,字符串"PQR"
没有作为匹配块找到。在
from difflib import SequenceMatcher
str1 = "ABCDPQRUVWXYZ"
str2 = "PQRABCDUVWXYZ"
matchAll = SequenceMatcher(None, str1, str2, False).get_matching_blocks()
for i in range(0, len(matchAll)):
print(str1[matchAll[i].a: matchAll[i].a + matchAll[i].size])
这可能是您想要的-但不会找到重叠的匹配项(修改为在子字符串的s1和s2中包括字符串位置):
印刷品:
^{pr2}$感谢所有回复我帖子的程序员。在
作为一种解决方案,我进行了试验,发现了另一种解决方案
方法。这基本上包括重复查找两个字符串之间的最长匹配,然后每次都用垃圾字符替换匹配的最长字符串。这也很管用。在
docs声明:
如果函数在您的示例中返回
"PQR"
,则j
不会单调增加,因为它将从"ABCD"
匹配的"A"
索引返回到"PQR"
匹配的"P"
索引。在相关问题 更多 >
编程相关推荐