计算两个字符串相似度的算法

该方法是使用的Levenshtein算法的一个实现。


 简单介绍下Levenshtein Distance(LD):LD 可能衡量两字符串的相似性。它们的距离就是一个字符串转换成那一个字符串过程中的添加、删除、修改数值。

    举例:

  • 如果str1="test",str2="test",那么LD(str1,str2) = 0。没有经过转换。
  • 如果str1="test",str2="tent",那么LD(str1,str2) = 1。str1的"s"转换"n",转换了一个字符,所以是1。

如果它们的距离越大,说明它们越是不同。

 

     Levenshtein distance最先是由俄国科学家Vladimir Levenshtein在1965年发明,用他的名字命名。不会拼读,可以叫它edit distance(编辑距离)。

 

    Levenshtein distance可以用来:

  • Spell checking(拼写检查)
  • Speech recognition(语句识别)
  • DNA analysis(DNA分析)
  • Plagiarism detection(抄袭检测)

LD用m*n的矩阵存储距离值。算法大概过程:

  1. str1或str2的长度为0返回另一个字符串的长度。
  2. 初始化(n+1)*(m+1)的矩阵d,并让第一行和列的值从0开始增长。
  3. 扫描两字符串(n*m级的),如果:str1[i] == str2[j],用temp记录它,为0。否则temp记为1。然后在矩阵d[i][j]赋于d[i-1][j]+1 、d[i][j-1]+1、d[i-1][j-1]+temp三者的最小值。
  4. 扫描完后,返回矩阵的最后一个值即d[n][m]

最后返回的是它们的距离。怎么根据这个距离求出相似度呢?因为它们的最大距离就是两字符串长度的最大值。对字符串不是很敏感。现我把相似度计算公式定为1-它们的距离/字符串长度最大值。


public static float similarity(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.charAt(i - 1) == str2.charAt(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);
			}
		}
		return 1 - (float) dif[len1][len2] / Math.max(str1.length(), str2.length());
	}
	
	//得到最小值
	public static int min(int... is) {
		int min = Integer.MAX_VALUE;
		for (int i : is) {
			if (min > i) {
				min = i;
			}
		}
		return min;
	}


以下是一个Java工具类,基于余弦相似度方法计算两个字符串相似度: ```java import java.util.HashMap; import java.util.Map; public class StringSimilarityUtil { /** * 计算两个字符串的余弦相似度 * * @param str1 字符串1 * @param str2 字符串2 * @return 余弦相似度 */ public static double cosineSimilarity(String str1, String str2) { // 分词 String[] words1 = str1.split(" "); String[] words2 = str2.split(" "); // 统计词频 Map<String, Integer> freq1 = new HashMap<>(); Map<String, Integer> freq2 = new HashMap<>(); for (String word : words1) { freq1.merge(word, 1, Integer::sum); } for (String word : words2) { freq2.merge(word, 1, Integer::sum); } // 计算向量长度 double length1 = 0; double length2 = 0; for (Map.Entry<String, Integer> entry : freq1.entrySet()) { length1 += Math.pow(entry.getValue(), 2); } for (Map.Entry<String, Integer> entry : freq2.entrySet()) { length2 += Math.pow(entry.getValue(), 2); } length1 = Math.sqrt(length1); length2 = Math.sqrt(length2); // 计算内积 double dotProduct = 0; for (Map.Entry<String, Integer> entry : freq1.entrySet()) { if (freq2.containsKey(entry.getKey())) { dotProduct += entry.getValue() * freq2.get(entry.getKey()); } } // 计算余弦相似度 return dotProduct / (length1 * length2); } } ``` 使用方法: ```java public static void main(String[] args) { String str1 = "Java是一种计算机编程语言"; String str2 = "Java是一种面向对象的编程语言"; double similarity = StringSimilarityUtil.cosineSimilarity(str1, str2); System.out.println(similarity); // 输出:0.6666666666666667 } ``` 其中,余弦相似度计算公式为: $$ similarity = \frac{\sum_{i=1}^{n} A_i \times B_i}{\sqrt{\sum_{i=1}^{n} A_i^2} \times \sqrt{\sum_{i=1}^{n} B_i^2}} $$ 其中,$A_i$和$B_i$分别表示两个字符串中第$i$个词的频次,$n$为总词数。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值