以下を考えると、最長の共通部分文字列を見つけることができます:
s1 = "this is a foo bar sentence ."
s2 = "what the foo bar blah blah black sheep is doing ?"
def longest_common_substring(s1, s2):
m = [[0] * (1 + len(s2)) for i in xrange(1 + len(s1))]
longest, x_longest = 0, 0
for x in xrange(1, 1 + len(s1)):
for y in xrange(1, 1 + len(s2)):
if s1[x - 1] == s2[y - 1]:
m[x][y] = m[x - 1][y - 1] + 1
if m[x][y] > longest:
longest = m[x][y]
x_longest = x
else:
m[x][y] = 0
return s1[x_longest - longest: x_longest]
print longest_common_substring(s1, s2)
[アウト]:
foo bar
しかし、最長の共通部分文字列が英語の単語の境界を尊重し、単語を切り詰めないようにするにはどうすればよいでしょうか? たとえば、次の文:
s1 = "this is a foo bar sentence ."
s2 = "what a kappa foo bar black sheep ?"
print longest_common_substring(s1, s2)
s2 から単語を分割するため、望ましくないフォローを出力します。kappa
a foo bar
目的の出力は次のとおりです。
foo bar
単語境界に関して最長の共通部分文字列を取得する ngram の方法も試しましたが、ngrams を計算せずに文字列を処理する他の方法はありますか? (答えを見てください)