c#计算文本相似度

 public static double TextSimilarityCalculator(string text1, string text2, bool isCase = false)
    {
        //if (string.IsNullOrEmpty(text1) || string.IsNullOrEmpty(text2))
        if (text1.Length <= 0 || text2.Length <= 0)
        {
            return (0);
        }
        if (!isCase)
        {
            text1 = text1.ToLower();
            text2 = text2.ToLower();
        }
        int[,] dp = new int[Math.Max(text1.Length, text2.Length) + 1, Math.Max(text1.Length, text2.Length) + 1];
        for (int x = 0; x < text1.Length; x++)
        {
            for (int y = 0; y < text2.Length; y++)
            {
                if (text1[x] == text2[y])
                {
                    dp[x + 1, y + 1] = dp[x, y] + 1;
                }
                else
                {
                    dp[x + 1, y + 1] = Math.Max(dp[x, y + 1], dp[x + 1, y]);
                }
            }
        }
        return (Math.Round(((double)(dp[text1.Length, text2.Length]) / Math.Max(text1.Length, text2.Length)) * 100, 2));
    }
 public static double TextSimilarityCalculator(string text1, string text2)
        {
            // 计算文本1的词频向量
            var vector1 = text1.GroupBy(word => word)
                               .ToDictionary(group => group.Key, group => group.Count());

            // 计算文本2的词频向量
            var vector2 = text2.GroupBy(word => word)
                               .ToDictionary(group => group.Key, group => group.Count());

            // 计算余弦相似度
            double dotProduct = vector1.Select(kv => kv.Value * 
                                vector2.GetValueOrDefault(kv.Key, 0)).Sum();
            double magnitude1 = Math.Sqrt(vector1.Values.Select(count => count * 
                                count).Sum());
            double magnitude2 = Math.Sqrt(vector2.Values.Select(count => count * 
                                count).Sum());

            if (magnitude1 == 0 || magnitude2 == 0)
            {
                return 0.0; // 避免除以零错误
            }

            return (dotProduct / (magnitude1 * magnitude2)) * 100;
        }

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值