【问题标题】:Algorithm to measure similarity between two sequences of strings测量两个字符串序列之间相似性的算法
【发布时间】:2016-06-16 10:32:25
【问题描述】:

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

我有两个文本文件,文件中的序列写成这样

第一个文件:

AAA BBB DDD CCC GGG MMM AAA MMM

第二个文件:

BBB DDD CCC MMM AAA MMM

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

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

【问题讨论】:

    标签: sequences


    【解决方案1】:

    您可以使用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].
    

    【讨论】:

      【解决方案2】:

      您可以使用 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指的是什么?
      猜你喜欢
      • 2019-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-15
      • 2019-04-18
      • 2021-10-12
      相关资源
      最近更新 更多