【转】关键字过滤算法
生活随笔
收集整理的這篇文章主要介紹了
【转】关键字过滤算法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
?
using System; using System.Collections.Generic; using System.Text; using System.Data; using System.Collections;namespace BLL.Common {#region 操作類public class KeywordsFilter{#region 關鍵字過濾/// <summary>/// 關鍵字過濾/// /// </summary>/// <param name="keywords"></param>/// <returns></returns>public static string Filter(string keywords){//需過濾關鍵字集合List<string> badwords = new List<string>();KeywordsFilterClass kf = new KeywordsFilterClass();keywords = kf.BadwordInKeywords(keywords, badwords);return keywords;}#endregion}#endregion#region 關鍵字過濾類/// <summary>/// 關鍵字過濾類/// </summary>public class KeywordsFilterClass{private Dictionary<string, object> hash = new Dictionary<string, object>();//臟字字典 開頭臟字存儲private BitArray firstCharCheck = new BitArray(char.MaxValue);//臟字字典 單個char存儲private BitArray allCharCheck = new BitArray(char.MaxValue);private int maxLength = 0;/// <summary>/// 初始化 已存儲的 過濾字符串/// </summary>/// <param name="words"></param>private void InitHash(List<string> badwords){foreach (string word in badwords){//保存字典內不存在的臟字if (!hash.ContainsKey(word)){hash.Add(word, null);//設置臟字計算長度this.maxLength = Math.Max(this.maxLength, word.Length);firstCharCheck[word[0]] = true;foreach (char c in word){allCharCheck[c] = true;}}}}/// <summary>/// 替換字符串中的臟字為指定的字符/// </summary>/// <param name="text"></param>/// <returns></returns>public string BadwordInKeywords(string text, List<string> badwords){//初始化 臟字字典this.InitHash(badwords);int index = 0;while (index < text.Length){//判斷開頭臟字if (!firstCharCheck[text[index]]){//未找到開頭臟字 則索引累加while (index < text.Length - 1 && !firstCharCheck[text[++index]]) ;}for (int j = 1; j <= Math.Min(maxLength, text.Length - index); j++){if (!allCharCheck[text[index + j - 1]]){break;}string sub = text.Substring(index, j);if (hash.ContainsKey(sub)){text = text.Replace(sub, "**");//this.InitHash(badwords);index += j;break;}}index++;}return text;}}#endregion }?
轉載于:https://www.cnblogs.com/TiestoRay/articles/2686115.html
總結
以上是生活随笔為你收集整理的【转】关键字过滤算法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ADDS学习(下)
- 下一篇: Linux——软件包简单学习笔记