1. 程式人生 > >Levenshtein計算字符串的相似度

Levenshtein計算字符串的相似度

差異 eve style blog oid write str2 字符 取數

        static void Main(string[] args)
        {

            Levenshtein(@"今天天氣不錯", @"今天的天氣不錯啊");

            Console.Read();
        }

        /// <summary>
        /// 字符串相似度計算
        /// </summary>
        /// <param name="str1"></param>
        /// <param name="str2"></param>
public static void Levenshtein(String str1, String str2) { //計算兩個字符串的長度。 int len1 = str1.Length; int len2 = str2.Length; //建立上面說的數組,比字符長度大一個空間 int[,] dif = new int[len1 + 1, len2 + 1]; //賦初值,步驟B。 for
(int a = 0; a <= len1; a++) { dif[a, 0] = a; } for (int a = 0; a <= len2; a++) { dif[0, a] = a; } //計算兩個字符是否一樣,計算左上的值 int temp; for (int i = 1; i <= len1; i++) {
for (int j = 1; j <= len2; j++) { if (str1[i - 1] == str2[j - 1]) { temp = 0; } else { temp = 1; } //取三個值中最小的 dif[i, j] = min(dif[i - 1, j - 1] + temp, dif[i, j - 1] + 1, dif[i - 1, j] + 1); } } Console.WriteLine("字符串\"" + str1 + "\"與\"" + str2 + "\"的比較"); //取數組右下角的值,同樣不同位置代表不同字符串的比較 Console.WriteLine("差異步驟:" + dif[len1, len2]); //計算相似度 float similarity = 1 - (float)dif[len1, len2] / Math.Max(str1.Length, str2.Length); Console.WriteLine("相似度:" + similarity + " 越接近1越相似"); } /// <summary> /// 得到最小值 /// </summary> /// <param name="num"></param> /// <returns></returns> private static int min(params int[] num) { int min = Int32.MaxValue; foreach (var n in num) { if (min > n) { min = n; } } return min; }

Levenshtein計算字符串的相似度