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

Dhe*_*wal 7 sequences

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

我有两个文本文件和In文件,序列写得像

第一档:

AAA BBB DDD CCC GGG MMM AAA MMM

第二档:

BBB DDD CCC MMM AAA MMM

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

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

ale*_*exn 8

您可以使用Levenstein距离算法.它分析了将一个字符串转换为另一个字符串所需的编辑次数.文章解释了它相当不错,并提供一个样本实现.

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].
Run Code Online (Sandbox Code Playgroud)


小智 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
Run Code Online (Sandbox Code Playgroud)

我希望这可以帮到你!