文本相似度——编辑距离

时间:2022-07-24
本文章向大家介绍文本相似度——编辑距离,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

1 基本思路

2 算法基本步骤

3 算法实现

3.1 递归

递归实现

int edit_distance(char *a, char *b, int i, int j)
{
    if (j == 0) {
        return i;
    } else if (i == 0) {
        return j;
    // 算法中 a, b 字符串下标从 1 开始,c 语言从 0 开始,所以 -1
    } else if (a[i-1] == b[j-1]) {
        return edit_distance(a, b, i - 1, j - 1);
    } else {
        return min_of_three(edit_distance(a, b, i - 1, j) + 1,
                            edit_distance(a, b, i, j - 1) + 1,
                            edit_distance(a, b, i - 1, j - 1) + 1);
    }
}

edit_distance(stra, strb, strlen(stra), strlen(strb));

使用递归性能低下,有很多子问题已经求解过,所以使用动态规划

3.2 动态规划

动态规划实现

int edit_distance(char *a, char *b)
{
    int lena = strlen(a);
    int lenb = strlen(b);
    int d[lena+1][lenb+1];
    int i, j;

    for (i = 0; i <= lena; i++) {
        d[i][0] = i;
    }
    for (j = 0; j <= lenb; j++) {
        d[0][j] = j;
    }

    for (i = 1; i <= lena; i++) {
        for (j = 1; j <= lenb; j++) {
            // 算法中 a, b 字符串下标从 1 开始,c 语言从 0 开始,所以 -1
            if (a[i-1] == b[j-1]) {
                d[i][j] = d[i-1][j-1];
            } else {
                d[i][j] = min_of_three(d[i-1][j]+1, d[i][j-1]+1, d[i-1][j-1]+1);
            }
        }
    }

    return d[lena][lenb];
}

3.3 Python 使用包

使用之前使用pip安装Levenshtein

pip install python-Levenshtein

import Levenshtein
string_1 = "jerry"
string_2 = "jary"
Levenshtein.distance(','.join(string_1), ','.join(string_2))
  1. https://www.dreamxu.com/books/dsa/dp/edit-distance.html
  2. https://www.dreamxu.com/books/dsa/dp/edit-distance.html