国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C# > 正文

C#和SQL實現的字符串相似度計算代碼分享

2020-01-24 02:22:49
字體:
來源:轉載
供稿:網友

C#實現:

復制代碼 代碼如下:

#region 計算字符串相似度
        /// <summary>
        /// 計算字符串相似度
        /// </summary>
        /// <param name="str1">字符串1</param>
        /// <param name="str2">字符串2</param>
        /// <returns>相似度</returns>
        public static float Levenshtein(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.Substring(i - 1, 1) == str2.Substring(j - 1, 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);
        }
        #endregion

        //比較3個數字得到最小值 
        private static int Min(int i, int j, int k)
        {
            return i < j ? (i < k ? i : k) : (j < k ? j : k);
        }

SQL實現:

復制代碼 代碼如下:

CREATE   function get_semblance_By_2words
(
@word1 varchar(50),
@word2 varchar(50)  
)
returns nvarchar(4000)
as
begin
declare @re int
declare @maxLenth int
declare @i int,@l int
declare @tb1 table(child varchar(50))
declare @tb2 table(child varchar(50))
set @i=1
set @l=2
set @maxLenth=len(@word1)
if len(@word1)<len(@word2) 
begin
set @maxLenth=len(@word2)
end
while @l<=len(@word1) 
begin
while @i<len(@word1)-1
begin
insert @tb1 (child) values( SUBSTRING(@word1,@i,@l) ) 
set @i=@i+1
end
set @i=1
set @l=@l+1
end
set @i=1
set @l=2
while @l<=len(@word2) 
begin
while @i<len(@word2)-1
begin
insert @tb2 (child) values( SUBSTRING(@word2,@i,@l) ) 
set @i=@i+1
end
set @i=1
set @l=@l+1
end  
select @re=isnull(max( len(a.child)*100/  @maxLenth ) ,0) from @tb1 a, @tb2 b where a.child=b.child
return @re
end
GO
 
--測試
--select dbo.get_semblance_By_2words('我是誰','我是誰啊') 
--75
--相似度

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 长武县| 中方县| 平陆县| 常山县| 九龙城区| 潢川县| 临邑县| 镇雄县| 凤山县| 恩施市| 乌鲁木齐县| 司法| 上思县| 喜德县| 南澳县| 丹寨县| 宝鸡市| 谢通门县| 肥乡县| 公主岭市| 石台县| 中超| 梓潼县| 长泰县| 精河县| 汝阳县| 新营市| 泗阳县| 米易县| 大石桥市| 老河口市| 祁东县| 玉溪市| 镇宁| 大洼县| 贵南县| 鹤壁市| 山丹县| 肥城市| 垫江县| 尚志市|