以上所有方法的完整代码如下,使用SimilarityUtil.getSimilarity(String s1,String s2)即可得到s1和s2的语句相似度:
package com.yuantu.dubbo.provider.questionRepo.utils;
import com.hankcs.hanlp.HanLP;
import com.hankcs.hanlp.dictionary.CustomDictionary;
import org.jsoup.Jsoup;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
public class SimilarityUtil {
static {
CustomDictionary.add("子类");
CustomDictionary.add("父类");
}
private SimilarityUtil() {
}
/**
* 获得两个句子的相似度
*
* @param sentence2
* @return
*/
public static double getSimilarity(String sentence1, String sentence2) {
List sent1Words = getSplitWords(sentence1);
System.out.println(sent1Words);
List sent2Words = getSplitWords(sentence2);
System.out.println(sent2Words);
List allWords = mergeList(sent1Words, sent2Words);
int[] statistic1 = statistic(allWords, sent1Words);
int[] statistic2 = statistic(allWords, sent2Words);
double dividend = 0;
double divisor1 = 0;
double divisor2 = 0;
for (int i = 0; i < statistic1.length; i++) {
dividend += statistic1 * statistic2;
divisor1 += Math.pow(statistic1, 2);
divisor2 += Math.pow(statistic2, 2);
}
return dividend / (Math.sqrt(divisor1) * Math.sqrt(divisor2));
}
private static int[] statistic(List allWords, List sentWords) {
int[] result = new int[allWords.size()];
for (int i = 0; i < allWords.size(); i++) {
result = Collections.frequency(sentWords, allWords.get(i));
}
return result;
}
private static List mergeList(List list1, List list2) {
List result = new ArrayList<>();
result.addAll(list1);
result.addAll(list2);
return result.stream().distinct().collect(Collectors.toList());
}
private static List getSplitWords(String sentence) {
// 去除掉html标签
sentence = Jsoup.parse(sentence.replace(" ","")).body().text();
// 标点符号会被单独分为一个Term,去除之
return HanLP.segment(sentence).stream().map(a -> a.word).filter(s -> !"`~!@#$^&*()=|{}':;',\[\].<>/?~!@#¥……&*()——|{}【】‘;:”“'。,、? ".contains(s)).collect(Collectors.toList());
}
}
---------------------