python – 用于多个输入的SequenceMatcher,而不仅仅是两个?

想知道解决这个特定问题的最佳方法,如果有任何库(最好是
python,但如果需要,我可以灵活).

我有一个文件,每行都有一个字符串.我想在每一行找到最长的常见模式及其位置.我知道我可以使用SequenceMatcher来比较第一行和第二行,第一行和第三行,然后将结果关联起来,但是如果已经有了它的话呢?

理想情况下,这些匹配会出现在每一行的任何位置,但对于初学者我可以很好地使用它们存在于每行的相同偏移处并从那里开始.像压缩库这样的东西有一个很好的API来访问它的字符串表可能是理想的,但我还没有发现任何适合该描述的东西.

例如,这些行:

\x00\x00\x8c\x9e\x28\x28\x62\xf2\x97\x47\x81\x40\x3e\x4b\xa6\x0e\xfe\x8b
\x00\x00\xa8\x23\x2d\x28\x28\x0e\xb3\x47\x81\x40\x3e\x9c\xfa\x0b\x78\xed
\x00\x00\xb5\x30\xed\xe9\xac\x28\x28\x4b\x81\x40\x3e\xe7\xb2\x78\x7d\x3e

我想看到0-1和10-12匹配在同一位置的所有行,line1 [4,5]匹配line2 [5,6]匹配line3 [7,8].

谢谢,

最佳答案 如果你想要的只是找到每行中相同偏移量的公共子串,你只需要这样:

matches = []
zipped_strings = zip(s1,s2,s3)
startpos = -1
for i in len(zipped_strings):
  c1,c2,c3 = zipped_strings[i]
  # if you're not inside a match, 
  #  look for matching characters and save the match start position
  if startpos==-1 and c1==c2==c3:
    startpos = i
  # if you are inside a match, 
  #  look for non-matching characters, save the match to matches, reset startpos
  elif startpos>-1 and not c1==c2==c3:
    matches.append((startpos,i,s1[startpos:i]))
    # matches will contain (startpos,endpos,matchstring) tuples
    startpos = -1
# if you're still inside a match when you run out of string, save that match too!
if startpos>-1:
  endpos = len(zipped_strings)
  matches.append((startpos,endpos,s1[startpos:endpos]))

要找到最长的常见模式而不考虑位置,SequenceMatcher听起来像是最好的想法,但不是将string1与string2进行比较,然后将string1与string3进行比较并尝试合并结果,只需获取string1和string2的所有常见子串(使用get_matching_blocks) ,然后将其中的每个结果与string3进行比较,以获得所有三个字符串之间的匹配.

点赞