两个字符串序列相似度的算法

7
如何测量两个字符串序列之间的相似度百分比?
我有两个文本文件,文件中写有以下字符串序列:
第一个文件:
AAA BBB DDD CCC GGG MMM AAA MMM
第二个文件:
BBB DDD CCC MMM AAA MMM
如何通过字符串顺序来衡量这两个文件之间的相似性?
例如,在上面的示例中,由于字符串的顺序相同,因此两个文件具有相似性,但是某些字符串在文件2中缺失。什么算法最适合解决此问题,以便我可以衡量两个文件中字符串顺序的相似程度而不是字符串频率?
2个回答

9
你可以使用Levenstein Distance算法。它分析需要多少次编辑才能将一个字符串转换为另一个字符串。这篇文章解释得很好,并提供了一个示例实现。
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].

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

我希望您能受益于以下信息!

2.0指的是什么? - Fatima

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接