1 package cph; 2 3 import java.util.HashMap; 4 import java.util.Iterator; 5 import java.util.Map; 6 7 public class SimilarDegreeByCos 8 { 9 /* 10 * 计算两个字符串(英文字符)的相似度,简单的余弦计算,未添权重 11 */ 12 public static double getSimilarDegree(String str1, String str2) 13 { 14 //创建向量空间模型,使用map实现,主键为词项,值为长度为2的数组,存放着对应词项在字符串中的出现次数 15 Map<String, int[]> vectorSpace = new HashMap<String, int[]>(); 16 int[] itemCountArray = null;//为了避免频繁产生局部变量,所以将itemCountArray声明在此 17 18 //以空格为分隔符,分解字符串 19 String strArray[] = str1.split(" "); 20 for(int i=0; i<strArray.length; ++i) 21 { 22 if(vectorSpace.containsKey(strArray[i])) 23 ++(vectorSpace.get(strArray[i])[0]); 24 else 25 { 26 itemCountArray = new int[2]; 27 itemCountArray[0] = 1; 28 itemCountArray[1] = 0; 29 vectorSpace.put(strArray[i], itemCountArray); 30 } 31 } 32 33 strArray = str2.split(" "); 34 for(int i=0; i<strArray.length; ++i) 35 { 36 if(vectorSpace.containsKey(strArray[i])) 37 ++(vectorSpace.get(strArray[i])[1]); 38 else 39 { 40 itemCountArray = new int[2]; 41 itemCountArray[0] = 0; 42 itemCountArray[1] = 1; 43 vectorSpace.put(strArray[i], itemCountArray); 44 } 45 } 46 47 //计算相似度 48 double vector1Modulo = 0.00;//向量1的模 49 double vector2Modulo = 0.00;//向量2的模 50 double vectorProduct = 0.00; //向量积 51 Iterator iter = vectorSpace.entrySet().iterator(); 52 53 while(iter.hasNext()) 54 { 55 Map.Entry entry = (Map.Entry)iter.next(); 56 itemCountArray = (int[])entry.getValue(); 57 58 vector1Modulo += itemCountArray[0]*itemCountArray[0]; 59 vector2Modulo += itemCountArray[1]*itemCountArray[1]; 60 61 vectorProduct += itemCountArray[0]*itemCountArray[1]; 62 } 63 64 vector1Modulo = Math.sqrt(vector1Modulo); 65 vector2Modulo = Math.sqrt(vector2Modulo); 66 67 //返回相似度 www.2cto.com 68 return (vectorProduct/(vector1Modulo*vector2Modulo)); 69 } 70 71 /* 72 * 73 */ 74 public static void main(String args[]) 75 { 76 String str1 = "好 好 好 好 好 好 你 陈 朋 辉 好"; 77 String str2 = "你 李 勋 好 好 好 好 好 好 好 好"; 78 String str3 = "你 是 个 大 好 人"; 79 String str4 = "你 今 天 好 吗"; 80 String str5 = "你 好"; 81 82 System.out.println(SimilarDegreeByCos.getSimilarDegree(str1, str2)); 83 System.out.println(SimilarDegreeByCos.getSimilarDegree(str1, str3)); 84 System.out.println(SimilarDegreeByCos.getSimilarDegree(str1, str4)); 85 System.out.println(SimilarDegreeByCos.getSimilarDegree(str1, str5)); 86 } 87 }
爬虫技术交流_crawler QQ群: 167047843