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

时间:2010-04-01 19:01:53

标签: python compression 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]。

谢谢,

2 个答案:

答案 0 :(得分:2)

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

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进行比较,以获得所有三个字符串之间的匹配。

答案 1 :(得分:0)

你的问题表现如何?

您的投入有多大?

最小字符串长度是否匹配2?

请注意,您的示例不正确我认为您期望的结果与您提供的示例字符串不匹配。