C# 敏感词过滤算法实现

开发 后端 算法
DFA即Deterministic Finite Automaton,也就是确定有穷自动机,它是是通过event和当前的state得到下一个state,即event+state=nextstate。在实现敏感词过滤的算法中,我们必须要减少运算,而DFA在DFA算法中几乎没有什么计算,有的只是状态的转换。

 

本文转载自微信公众号「UP技术控」,作者conan 。转载本文请联系UP技术控公众号。

敏感词、文字过滤是一个网站必不可少的功能,如何设计一个好的、高效的过滤算法是非常有必要的。

在实现文字过滤的算法中,DFA是唯一比较好的实现算法。DFA即Deterministic Finite Automaton,也就是确定有穷自动机,它是是通过event和当前的state得到下一个state,即event+state=nextstate。在实现敏感词过滤的算法中,我们必须要减少运算,而DFA在DFA算法中几乎没有什么计算,有的只是状态的转换。

下面看下在c#方法下实现方式

1、构建敏感词库类

  1. private bool LoadDictionary() 
  2.        { 
  3.            var wordList = new List<string>(); 
  4.            if (_memoryLexicon == null
  5.            { 
  6.                _memoryLexicon = new WordGroup[char.MaxValue]; 
  7.                var words = new SensitiveWordBll().GetAllWords(); 
  8.                if (words == null
  9.                    return false
  10.                foreach (string word in words) 
  11.                { 
  12.                    wordList.Add(word); 
  13.                    var chineseWord = Microsoft.VisualBasic.Strings.StrConv(word, 
  14.                        Microsoft.VisualBasic.VbStrConv.TraditionalChinese, 0); 
  15.                    if (word != chineseWord) 
  16.                        wordList.Add(chineseWord); 
  17.                } 
  18.                foreach (var word in wordList) 
  19.                { 
  20.                    if (word.Length > 0) 
  21.                    { 
  22.                        var group = _memoryLexicon[word[0]]; 
  23.                        if (group == null
  24.                        { 
  25.                            group = new WordGroup(); 
  26.                            _memoryLexicon[word[0]] = group
  27.                        } 
  28.                        group.Add(word.Substring(1)); 
  29.                    } 
  30.                } 
  31.            } 
  32.            return true
  33.        } 

2、构建敏感词检测类

  1. private bool Check(string blackWord) 
  2.      { 
  3.          _wordlenght = 0; 
  4.          //检测源下一位游标 
  5.          _nextCursor = _cursor + 1; 
  6.          var found = false
  7.          var continueCheck = 0; 
  8.          //遍历词的每一位做匹配 
  9.          for (var i = 0; i < blackWord.Length; i++) 
  10.          { 
  11.              //特殊字符偏移游标 
  12.              var offset = 0; 
  13.              if (_nextCursor >= _sourceText.Length) 
  14.              { 
  15.                  if (i - 1 < blackWord.Length - 1) 
  16.                      found = false
  17.                  break; 
  18.              } 
  19.              else 
  20.              { 
  21.                  //检测下位字符如果不是汉字 数字 字符 偏移量加1 
  22.                  for (var y = _nextCursor; y < _sourceText.Length; y++) 
  23.                  { 
  24.                      if (!IsChs(_sourceText[y]) && !IsNum(_sourceText[y]) && !IsAlphabet(_sourceText[y])) 
  25.                      { 
  26.                          offset++; 
  27.                          //避让特殊字符,下位游标如果>=字符串长度 跳出 
  28.                          if (_nextCursor + offset >= _sourceText.Length) 
  29.                              break; 
  30.                          _wordlenght++; 
  31.                      } 
  32.                      else break; 
  33.                  } 
  34.                  if (_nextCursor + offset >= _sourceText.Length) 
  35.                  { 
  36.                      found = false
  37.                      break; 
  38.                  } 
  39.                  if (blackWord[i] == _sourceText[_nextCursor + offset]) 
  40.                  { 
  41.                      found = true
  42.                      continueCheck = 0; 
  43.                  } 
  44.                  else 
  45.                  { 
  46.                      // 匹配不到时尝试继续匹配4个字符 
  47.                      if (continueCheck < 4 && _nextCursor < _sourceText.Length - 1) 
  48.                      { 
  49.                          continueCheck++; 
  50.                          i--; 
  51.                      } 
  52.                      else 
  53.                      { 
  54.                          found = false
  55.                          break; 
  56.                      } 
  57.                  } 
  58.              } 
  59.              _nextCursor = _nextCursor + 1 + offset; 
  60.              _wordlenght++; 
  61.          } 
  62.          return found; 
  63.      } 
  64.  } 

3、测试与使用方法

  1. _illegalWords = new List<string>(); 
  2.           if (string.IsNullOrEmpty(sourceText) && string.IsNullOrEmpty(_sourceText)) 
  3.           { 
  4.               return sourceText; 
  5.           } 
  6.  
  7.           if (!string.IsNullOrEmpty(sourceText)) 
  8.               _sourceText = sourceText; 
  9.           _cursor = 0; 
  10.           if (!LoadDictionary()) 
  11.           { 
  12.               return _sourceText; 
  13.           } 
  14.  
  15.           var tempString = _sourceText.ToCharArray(); 
  16.           var sourceTextDbc = ToDBC(SourceText); 
  17.           for (var i = 0; i < SourceText.Length; i++) 
  18.           { 
  19.               //查询以该字为首字符的词组 
  20.               var group = _memoryLexicon[sourceTextDbc[i]]; 
  21.               if (group != null
  22.               { 
  23.                   for (var z = 0; z < group.Count(); z++) 
  24.                   { 
  25.                       string word = group.GetWord(z); 
  26.                       if (word.Length == 0 || Check(word)) 
  27.                       { 
  28.                           if (isFirstCheckedReturn) 
  29.                           { 
  30.                               return null
  31.                           } 
  32.  
  33.                           var blackword = string.Empty; 
  34.                           for (var pos = 0; pos < _wordlenght + 1; pos++) 
  35.                           { 
  36.                               blackword += tempString[pos + _cursor].ToString(); 
  37.                               tempString[pos + _cursor] = ReplaceChar; 
  38.                           } 
  39.                           _illegalWords.Add(blackword); 
  40.  
  41.                           _cursor = _cursor + _wordlenght; 
  42.                           i = i + _wordlenght; 
  43.                           break; 
  44.                       } 
  45.                   } 
  46.               } 
  47.               _cursor++; 
  48.           } 
  49.           return new string(tempString); 
  1. var filter = new SensitiveWordFilter(); 
  2.            filter.SourceText = "dddddd"
  3.            var sourctText = filter.SourceText; 
  4.            filter.ResetMemoryLexicon(); 
  5.            var datetime = DateTime.Now; 
  6.            var ss = filter.Filter(); 
  7.            var datetime2 = DateTime.Now; 
  8.            var millisecond = (datetime2 - datetime).TotalMilliseconds; 
  9.            Console.WriteLine(millisecond); 
  10.            Console.WriteLine(ss); 
  11.            var words = System.IO.File.ReadAllLines(@"D:\Recv\敏感词库大全.txt", System.Text.Encoding.UTF8); 
  12.            var ssx = sourctText; 
  13.            var datetimex = DateTime.Now; 
  14.            foreach (var word in words) 
  15.            { 
  16.                if (word.Length > 0) 
  17.                    ssx = ssx.Replace(word, "*".PadLeft(word.Length, '*')); 
  18.            } 
  19.            var datetime2x = DateTime.Now; 
  20.            var millisecondx = (datetime2x - datetimex).TotalMilliseconds; 
  21.            Console.WriteLine(millisecondx); 
  22.            Console.WriteLine(ssx); 

 

 

责任编辑:武晓燕 来源: UP技术控
相关推荐

2023-10-27 08:46:34

DFA算法工具

2009-08-17 13:07:27

C#马赛克算法

2009-08-13 18:12:11

C#数据加密

2009-07-22 17:15:04

C#实现

2009-08-11 10:26:49

C#算法C#字符串反转

2009-08-11 13:54:54

约瑟夫环算法C#算法

2009-09-02 14:47:44

C#换行符

2009-08-11 13:20:45

高斯消元法C#算法

2009-08-11 13:29:57

C#二叉树遍历

2009-08-25 17:55:52

C#实现Strateg

2009-08-20 14:22:17

C#实现 Contro

2009-08-19 17:00:07

C#实现PrintPa

2009-08-31 15:55:17

C#实现Strateg

2009-08-11 15:09:44

一道面试题C#算法

2009-09-01 18:29:10

C#继承C#多态

2009-08-26 09:54:45

C#打印预览C#打印

2023-10-09 07:11:03

排序算法序列

2009-08-25 17:41:51

C#开发排序算法

2009-08-21 15:02:31

C#加密算法

2009-08-11 09:19:52

C#选择排序C#算法
点赞
收藏

51CTO技术栈公众号