这个比较文本用到的主要是余弦定理比较文本相似度,具体原理右转某度,主要适用场景是在考试系统中的简答题概述,可根据权重自动打分,感觉实用性蛮广的。

 

先说下思路:

  1. 文本分词,中文于英文不同,规范的英文每个都有空格自动分词,中文则是连成长串,我们只有一一比对每个词出现的频率做简单的比较,在这里使用到了SCWS的一个分词api接口http://www.ftphp.com/scws/api.php(仅支持POST,因为要模拟Http请求,所以请求时间也是根据具体环境而定,所以可以自己手写一些字典,本地分词要来的快)。但是用此接口分词过程中,标点符号不会被去掉,所以需要自己手动写方法去掉标点。
  2. 获取两个文本的去重复并集
  3. 比较每个词出现的频率
  4. 根据余弦定理计算权重

下面是具体的代码段(请求是在网上找的,原链接找不到了。。)

class Program
    {
        static void Main(string[] args)
        {
            Console.Write(Sim("床前明月光,疑是地上霜", "床前明月光,疑是地上霜"));
        }
        public static double Sim(string txt1, string txt2)
        {
            List<string> sl1 = Segment(txt1); 
            List<string> sl2 = Segment(txt2);
            //去重
            List<string> sl = sl1.Union(sl2).ToList<string>();
            //获取重复次数
            List<int> arrA = new List<int>();
            List<int> arrB = new List<int>();

            foreach (var str in sl)
            {
                arrA.Add(sl1.Where(x => x == str).Count());
                arrB.Add(sl2.Where(x => x == str).Count());
            }
            //计算商
            double num = 0;
            //被除数
            double numA = 0;
            double numB = 0;
            for (int i = 0; i < sl.Count; i++)
            {
                num += arrA[i] * arrB[i];
                numA += Math.Pow(arrA[i], 2);
                numB += Math.Pow(arrB[i], 2);
            }
            double cos = num / (Math.Sqrt(numA)* Math.Sqrt(numB));
            return cos;
        }
        public static List<string> Segment(string str)
        {
            List<string> sl = new List<string>();
            try
            {
                string s = string.Empty;
                System.Net.CookieContainer cookieContainer = new System.Net.CookieContainer();
                // 将提交的字符串数据转换成字节数组           
                byte[] postData = System.Text.Encoding.ASCII.GetBytes("data=" + System.Web.HttpUtility.UrlEncode(str) + "&respond=json&charset=utf8&ignore=yes&duality=no&traditional=no&multi=0");

                // 设置提交的相关参数
                System.Net.HttpWebRequest request = System.Net.WebRequest.Create("http://www.ftphp.com/scws/api.php") as System.Net.HttpWebRequest;
                request.Method = "POST";
                request.KeepAlive = false;
                request.ContentType = "application/x-www-form-urlencoded";
                request.CookieContainer = cookieContainer;
                request.ContentLength = postData.Length;

                // 提交请求数据
                System.IO.Stream outputStream = request.GetRequestStream();
                outputStream.Write(postData, 0, postData.Length);
                outputStream.Close();

                // 接收返回的页面
                System.Net.HttpWebResponse response = request.GetResponse() as System.Net.HttpWebResponse;
                System.IO.Stream responseStream = response.GetResponseStream();
                System.IO.StreamReader reader = new System.IO.StreamReader(responseStream, System.Text.Encoding.GetEncoding("utf-8"));
                string val = reader.ReadToEnd();

                Newtonsoft.Json.Linq.JObject results = Newtonsoft.Json.Linq.JObject.Parse(val);
                foreach (var item in results["words"].Children())
                {
                    Newtonsoft.Json.Linq.JObject word = Newtonsoft.Json.Linq.JObject.Parse(item.ToString());
                    var sss = word["word"].ToString();
                    //判断是否为标点符
                    bool offom = false;
                    foreach (char t in sss)
                    {
                        if (t >= 0x4e00 && t <= 0x9fbb)
                        {
                            offom = true;
                        }
                        else
                        {
                            offom = false;
                        }
                    }
                    if (offom)
                    {
                        sl.Add(sss);
                    }
                }
            }
            catch
            {
            }

            return sl;
        }
    }

  以上 感觉很多地方都可以优化,以后想到更好的再重新来一遍

 posted on 2017-09-29 11:36  Hi!Bro!  阅读(4575)  评论(0编辑  收藏  举报