using System;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace LumkitCms.Utils
{
    /// <summary>
    /// 分词类
    /// </summary>
    public static class WordSpliter
    {
        #region 属性
        private static string SplitChar = " ";//分隔符
        #endregion
        //
        #region 数据缓存函数
        /// <summary>
        /// 数据缓存函数
        /// </summary>
        /// <param name="key">索引键</param>
        /// <param name="val">缓存的数据</param>
        private static void SetCache(string key, object val)
        {
            if (val == null)
                val = " ";
            System.Web.HttpContext.Current.Application.Lock();
            System.Web.HttpContext.Current.Application.Set(key, val);
            System.Web.HttpContext.Current.Application.UnLock();
        }
        /// <summary>
        /// 读取缓存
        /// </summary>
        /// <param name="mykey"></param>
        /// <returns></returns>
        private static object GetCache(string key)
        {
            return System.Web.HttpContext.Current.Application.Get(key);
        }
        #endregion
        //
        #region 读取文本
        private static SortedList ReadTxtFile(string FilePath)
        {
            if (GetCache("cms_dict") == null)
            {
                Encoding encoding = Encoding.GetEncoding("utf-8");
                SortedList arrText = new SortedList();
                //
                try
                {
                    FilePath = System.Web.HttpContext.Current.Server.MapPath(FilePath);
                    if (!File.Exists(FilePath))
                    {
                        arrText.Add("0", "文件" + FilePath + "不存在...");
                    }
                    else
                    {
                        StreamReader objReader = new StreamReader(FilePath, encoding);
                        string sLine = "";
                        //ArrayList arrText = new ArrayList();

while (sLine != null)
                        {
                            sLine = objReader.ReadLine();
                            if (sLine != null)
                                arrText.Add(sLine, sLine);
                        }
                        //
                        objReader.Close();
                        objReader.Dispose();
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                SetCache("cms_dict", arrText);
            }
            return (SortedList)GetCache("cms_dict");
        }
        #endregion
        //
        #region 载入词典
        private static SortedList LoadDict(string dictfile)
        {
            return ReadTxtFile(dictfile);
        }
        #endregion
        //
        #region 判断某字符串是否在指定字符数组中
        private static bool StrIsInArray(string[] StrArray, string val)
        {
            for (int i = 0; i < StrArray.Length; i++)
                if (StrArray[i] == val) return true;
            return false;
        }
        #endregion
        //
        #region 正则检测
        private static bool IsMatch(string str, string reg)
        {
            return new Regex(reg).IsMatch(str);
        }
        #endregion
        //
        #region 首先格式化字符串(粗分)
        private static string FormatStr(string val)
        {
            string result = "";
            if (val == null || val == "")
                return "";
            //
            char[] CharList = val.ToCharArray();
            //
            string Spc = SplitChar;//分隔符
            int StrLen = CharList.Length;
            int CharType = 0; //0-空白 1-英文 2-中文 3-符号
            //
            for (int i = 0; i < StrLen; i++)
            {
                string StrList = CharList[i].ToString();
                if (StrList == null || StrList == "")
                    continue;
                //
                if (CharList[i] < 0x81)
                {
                    #region
                    if (CharList[i] < 33)
                    {
                        if (CharType != 0 && StrList != "/n" && StrList != "/r")
                        {
                            result += " ";
                            CharType = 0;
                        }
                        continue;
                    }
                    else if (IsMatch(StrList, "[^0-9a-zA-Z@//.%#:///&_-]"))//排除这些字符
                    {
                        if (CharType == 0)
                            result += StrList;
                        else
                            result += Spc + StrList;
                        CharType = 3;
                    }
                    else
                    {
                        if (CharType == 2 || CharType == 3)
                        {
                            result += Spc + StrList;
                            CharType = 1;
                        }
                        else
                        {
                            if (IsMatch(StrList, "[@%#:]"))
                            {
                                result += StrList;
                                CharType = 3;
                            }
                            else
                            {
                                result += StrList;
                                CharType = 1;
                            }//end if No.4
                        }//end if No.3
                    }//end if No.2
                    #endregion
                }//if No.1
                else
                {
                    //如果上一个字符为非中文和非空格,则加一个空格
                    if (CharType != 0 && CharType != 2)
                        result += Spc;
                    //如果是中文标点符号
                    if (!IsMatch(StrList, "^[/u4e00-/u9fa5]+$"))
                    {
                        if (CharType != 0)
                            result += Spc + StrList;
                        else
                            result += StrList;
                        CharType = 3;
                    }
                    else //中文
                    {
                        result += StrList;
                        CharType = 2;
                    }
                }
                //end if No.1

}//exit for
            //
            return result;
        }
        #endregion
        //
        #region 分词
        /// <summary>
        /// 分词
        /// </summary>
        /// <param name="key">关键词</param>
        /// <returns></returns>
        private static ArrayList StringSpliter(string[] key, string dictfile)
        {
            ArrayList List = new ArrayList();
            try
            {
                SortedList dict = LoadDict(dictfile);//载入词典
                //
                for (int i = 0; i < key.Length; i++)
                {
                    if (IsMatch(key[i], @"^(?!^/.$)([a-zA-Z0-9/./u4e00-/u9fa5]+)$")) //中文、英文、数字
                    {
                        if (IsMatch(key[i], "^[/u4e00-/u9fa5]+$"))//如果是纯中文
                        {
                            int keyLen = key[i].Length;
                            if (keyLen < 2)
                                continue;
                            else if (keyLen <= 7)
                                List.Add(key[i]);
                            //开始分词
                            for (int x = 0; x < keyLen; x++)
                            {
                                //x:起始位置//y:结束位置
                                for (int y = x; y < keyLen; y++)
                                {
                                    string val = key[i].Substring(x, keyLen - y);
                                    if (val == null || val.Length < 2)
                                        break;
                                    else if (val.Length > 10)
                                        continue;
                                    if (dict.Contains(val))
                                        List.Add(val);
                                }
                            }
                        }
                        else if (!IsMatch(key[i], @"^(/.*)$"))//不全是小数点
                        {
                            List.Add(key[i]);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return List;
        }
        #endregion
        //
        #region 得到分词结果
        /// <summary>
        /// 得到分词结果
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string[] DoSplit(string key, string dictfile)
        {
            ArrayList KeyList = StringSpliter(FormatStr(key).Split(SplitChar.ToCharArray()), dictfile);
            KeyList.Insert(0, key);
            //去掉重复的关键词
            for (int i = 0; i < KeyList.Count; i++)
            {
                for (int j = 0; j < KeyList.Count; j++)
                {
                    if (KeyList[i].ToString() == KeyList[j].ToString())
                    {
                        if (i != j)
                        {
                            KeyList.RemoveAt(j); j--;
                        }
                    }
                }
            }
            return (string[])KeyList.ToArray(typeof(string));
        }
        /// <summary>
        /// 得到分词关键字,以逗号隔开
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string GetKeyword(string key, string dictfile)
        {
            string _value = "";
            string[] _key = DoSplit(key, dictfile);
            for (int i = 1; i < _key.Length; i++)
            {
                if (i == 1)
                    _value = _key[i].Trim();
                else
                    _value += "," + _key[i].Trim();
            }
            return _value;
        }
        #endregion
    }
}

关键词提取1-C#的更多相关文章

  1. TextRank:关键词提取算法中的PageRank

    很久以前,我用过TFIDF做过行业关键词提取.TFIDF仅仅从词的统计信息出发,而没有充分考虑词之间的语义信息.现在本文将介绍一种考虑了相邻词的语义关系.基于图排序的关键词提取算法TextRank [ ...

  2. HanLP 关键词提取算法分析

    HanLP 关键词提取算法分析 参考论文:<TextRank: Bringing Order into Texts> TextRank算法提取关键词的Java实现 TextRank算法自动 ...

  3. python实现关键词提取

    今天我来弄一个简单的关键词提取的代码 文章内容关键词的提取分为三大步: (1) 分词 (2) 去停用词 (3) 关键词提取 分词方法有很多,我这里就选择常用的结巴jieba分词:去停用词,我用了一个停 ...

  4. 关键词提取算法TextRank

    很久以前,我用过TFIDF做过行业关键词提取.TFIDF仅仅从词的统计信息出发,而没有充分考虑词之间的语义信息.现在本文将介绍一种考虑了相邻词的语义关系.基于图排序的关键词提取算法TextRank. ...

  5. 自然语言处理工具hanlp关键词提取图解TextRank算法

    看一个博主(亚当-adam)的关于hanlp关键词提取算法TextRank的文章,还是非常好的一篇实操经验分享,分享一下给各位需要的朋友一起学习一下! TextRank是在Google的PageRan ...

  6. HanLP 关键词提取算法分析详解

    HanLP 关键词提取算法分析详解 l 参考论文:<TextRank: Bringing Order into Texts> l TextRank算法提取关键词的Java实现 l Text ...

  7. 关键词提取_textbank

    脱离语料库,仅对单篇文档提取 (1) pageRank算法:有向无权,平均分配贡献度 基本思路: 链接数量:一个网页越被其他的网页链接,说明这个网页越重要 链接质量:一个网页被一个越高权值的网页链接, ...

  8. NLP自然语言处理 jieba中文分词,关键词提取,词性标注,并行分词,起止位置,文本挖掘,NLP WordEmbedding的概念和实现

    1. NLP 走近自然语言处理 概念 Natural Language Processing/Understanding,自然语言处理/理解 日常对话.办公写作.上网浏览 希望机器能像人一样去理解,以 ...

  9. 关键词提取自动摘要相关开源项目,自动化seo

    关键词提取自动摘要相关开源项目 GitHub - hankcs/HanLP: 自然语言处理 中文分词 词性标注 命名实体识别 依存句法分析 关键词提取 自动摘要 短语提取 拼音 简繁转换https:/ ...

  10. 关键词提取算法-TextRank

    今天要介绍的TextRank是一种用来做关键词提取的算法,也可以用于提取短语和自动摘要.因为TextRank是基于PageRank的,所以首先简要介绍下PageRank算法. 1.PageRank算法 ...

随机推荐

  1. 总有一天会NB的! SB一样的坚持会有NB一样的结果的!

    第一天: 1.背景图不显示,因为背景图片无法撑开div,所以必须自己设置div的高度哦! 2.div水平居中! A:margin-left:auto;margin-right:auto;  B: 父元 ...

  2. __getattribute__

    class Foo: def __init__(self,x): self.x = x def __getattribute__(self, item): print('不管是否纯在,我都会执行') ...

  3. 【UOJ #20】【NOIP 2014】解方程

    http://uoj.ac/problem/20 并不会做...然后看题解....... 对a取模,避免了高精度带来的复杂度,然后再枚举x判断是否满足模意义下等于0. 取5个模数,我直接抄的别人的_( ...

  4. swift 学习(二)基础知识 (函数,闭包,ARC,柯里化,反射)

    函数 func x(a:Int, b:Int)  {}   func x(a:Int, b:Int) -> Void {}  func x(a:Int, b:Int) ->(Int,Int ...

  5. ajax技术应用(转)

    ajax简介 AJAX即"Asynchronous Javascript And XML"(异步JavaScript和XML),是指一种创建交互式网页应用的网页开发技术.Ajax不 ...

  6. C#-WinForm-打开其他窗体的三种方式-Show()、设置Owner()、ShowDialog()

    打开其他窗体的三种方式 Show - 例如登入界面进入主页面,直接将主页面展示出来,两个窗体互不影响 public partial class Form1 : Form { public Form1( ...

  7. .VDI manual Technical Logistics - Volume 2: Industrial Trucks

    VDI manual Technical Logistics - Volume 2: Industrial Trucks Name Publication date: State VDI 2196 B ...

  8. 【bzoj2456】 mode

    http://www.lydsy.com/JudgeOnline/problem.php?id=2456 (题目链接) 只看了一眼,直觉便告诉我这是水题.于是跟某码农打赌说10分钟做出来叫爸爸,结果输 ...

  9. phpize报cannot find autoconf

    突然想往php种增加个模块,可是又不想重新编译php,因为真的比较费时间. phpize就可以解决这个问题. 遇到的问题: Configuring for: PHP Api Version: Zend ...

  10. SELINUX、Security Access Control Strategy && Method And Technology Research - 安全访问控制策略及其方法技术研究

    catalog . 引言 . 访问控制策略 . 访问控制方法.实现技术 . SELINUX 0. 引言 访问控制是网络安全防范和客户端安全防御的主要策略,它的主要任务是保证资源不被非法使用.保证网络/ ...