C((zhi Net)は2文字列の類似度を比較します(コサインの類似度を使用します)

5534 ワード

C((zhi Net)は2文字列の類似度を比較します(コサインの類似度を使用します)
使用:     /// /// 2 ( ) /// /// /// /// 0-1 public static double SimilarityCos(string str1, string str2) { str1 = str1.Trim(); str2 = str2.Trim(); if (string.IsNullOrEmpty(str1) || string.IsNullOrEmpty(str2)) return 0; List<string> lstr1 = SimpParticiple(str1); List<string> lstr2 = SimpParticiple(str2); // var strUnion = lstr1.Union(lstr2); // List<int> int1 = new List<int>(); List<int> int2 = new List<int>(); foreach (var item in strUnion) { int1.Add(lstr1.Count(o => o == item)); int2.Add(lstr2.Count(o => o == item)); } double s = 0; double den1 = 0; double den2 = 0; for (int i = 0; i < int1.Count(); i++) { // s += int1[i] * int2[i]; // (1) den1 += Math.Pow(int1[i], 2); // (2) den2 += Math.Pow(int2[i], 2); } return s / (Math.Sqrt(den1) * Math.Sqrt(den2)); } /// /// ( , , :【 】, 【 , , 】, ,【 】=【 】 ) /// public static List<string> SimpParticiple(string str) { List<string> vs = new List<string>(); foreach (var item in str) { vs.Add(item.ToString()); } return vs; }