Java計算文本相似度實現

ymny 9年前發布 | 94K 次閱讀 分詞 Java開發

word分詞提供了兩種文本相似度計算方式:

方式一:余弦相似度,通過計算兩個向量的夾角余弦值來評估他們的相似度

實現類:org.apdplat.word.analysis.CosineTextSimilarity

用法如下:

String text1 = "我愛學習";
String text2 = "我愛讀書";
String text3 = "他是黑客";
TextSimilarity textSimilarity = new CosineTextSimilarity();
double score1pk1 = textSimilarity.similarScore(text1, text1);
double score1pk2 = textSimilarity.similarScore(text1, text2);
double score1pk3 = textSimilarity.similarScore(text1, text3);
double score2pk2 = textSimilarity.similarScore(text2, text2);
double score2pk3 = textSimilarity.similarScore(text2, text3);
double score3pk3 = textSimilarity.similarScore(text3, text3);
System.out.println(text1+" 和 "+text1+" 的相似度分值:"+score1pk1);
System.out.println(text1+" 和 "+text2+" 的相似度分值:"+score1pk2);
System.out.println(text1+" 和 "+text3+" 的相似度分值:"+score1pk3);
System.out.println(text2+" 和 "+text2+" 的相似度分值:"+score2pk2);
System.out.println(text2+" 和 "+text3+" 的相似度分值:"+score2pk3);
System.out.println(text3+" 和 "+text3+" 的相似度分值:"+score3pk3);

運行結果如下:

我愛學習 和 我愛學習 的相似度分值:1.0
我愛學習 和 我愛讀書 的相似度分值:0.4
我愛學習 和 他是黑客 的相似度分值:0.0
我愛讀書 和 我愛讀書 的相似度分值:1.0
我愛讀書 和 他是黑客 的相似度分值:0.0
他是黑客 和 他是黑客 的相似度分值:1.0

方式二:簡單共有詞,通過計算兩篇文檔有多少個相同的詞來評估他們的相似度

實現類:org.apdplat.word.analysis.SimpleTextSimilarity

用法如下:

String text1 = "我愛學習";
String text2 = "我愛讀書";
String text3 = "他是黑客";
TextSimilarity textSimilarity = new SimpleTextSimilarity();
double score1pk1 = textSimilarity.similarScore(text1, text1);
double score1pk2 = textSimilarity.similarScore(text1, text2);
double score1pk3 = textSimilarity.similarScore(text1, text3);
double score2pk2 = textSimilarity.similarScore(text2, text2);
double score2pk3 = textSimilarity.similarScore(text2, text3);
double score3pk3 = textSimilarity.similarScore(text3, text3);
System.out.println(text1+" 和 "+text1+" 的相似度分值:"+score1pk1);
System.out.println(text1+" 和 "+text2+" 的相似度分值:"+score1pk2);
System.out.println(text1+" 和 "+text3+" 的相似度分值:"+score1pk3);
System.out.println(text2+" 和 "+text2+" 的相似度分值:"+score2pk2);
System.out.println(text2+" 和 "+text3+" 的相似度分值:"+score2pk3);
System.out.println(text3+" 和 "+text3+" 的相似度分值:"+score3pk3);

運行結果如下:

我愛學習 和 我愛學習 的相似度分值:1.0
我愛學習 和 我愛讀書 的相似度分值:0.5
我愛學習 和 他是黑客 的相似度分值:0.0
我愛讀書 和 我愛讀書 的相似度分值:1.0
我愛讀書 和 他是黑客 的相似度分值:0.0
他是黑客 和 他是黑客 的相似度分值:1.0

來自:http://my.oschina.net/apdplat/blog/417047

 本文由用戶 ymny 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!