测量两个字符串序列之间相似性的算法

时间:2012-06-01 05:55:47

标签: sequences

如何测量两个字符串序列之间的相似性百分比?

我有两个文本文件和In文件中的序列编写如

第一档:

  

AAA BBB DDD CCC GGG MMM AAA MMM

第二档:

  

BBB DDD CCC MMM AAA MMM

如何根据字符串的顺序来衡量这两个文件之间的相似性?

例如,在上面的示例中,由于字符串的顺序相同,两个文件都具有相似性,但文件-2中缺少某些字符串。什么算法最适合解决这个问题,以便我可以测量字符串的顺序与两个字符串的频率有多相似?

2 个答案:

答案 0 :(得分:8)

您可以使用Levenstein Distance算法。它分析了将一个字符串转换为另一个字符串所需的编辑次数。 This文章解释得非常好,并提供了示例实现。

Codeproject复制粘贴:

1.  Set n to be the length of s. ("GUMBO")
    Set m to be the length of t. ("GAMBOL")
    If n = 0, return m and exit.
    If m = 0, return n and exit.
    Construct two vectors, v0[m+1] and v1[m+1], containing 0..m elements.
2.  Initialize v0 to 0..m.
3.  Examine each character of s (i from 1 to n).
4.  Examine each character of t (j from 1 to m).
5.  If s[i] equals t[j], the cost is 0.
    If s[i] is not equal to t[j], the cost is 1.
6.  Set cell v1[j] equal to the minimum of:
    a. The cell immediately above plus 1: v1[j-1] + 1.
    b. The cell immediately to the left plus 1: v0[j] + 1.
    c. The cell diagonally above and to the left plus the cost: v0[j-1] + cost.
7.  After the iteration steps (3, 4, 5, 6) are complete, the distance is found in the cell v1[m].

答案 1 :(得分:6)

您可以使用python的SequenceMatcher.ratio函数,该函数将序列相似度测量为[0, 1]范围内的浮点数。如果 T 是两个序列中元素的总数, M 是匹配数,则为2.0 * M / T。主要代码如下:

from difflib import SequenceMatcher
text1 = 'AAA BBB DDD CCC GGG MMM AAA MMM'
text2 = 'BBB DDD CCC MMM AAA MMM'
s = SequenceMatcher(None, text1, text2)
similarity = s.ratio() * 100

我希望这可以帮到你!

相关问题