/// <summary> /// 敏感词检测 /// </summary> /// <param name="library">敏感词库</param> public ContentCheck(WordsLibrary library) { if (library.Library == null) { throw new Exception("敏感词库未初始化"); } Library = library.Library; }
/// <summary> /// 检测敏感词 /// </summary> /// <param name="text">检测文本</param> /// <returns></returns> private Dictionary <int, char> WordsCheck(string text) { if (Library == null) { throw new Exception("未设置敏感词库 词树"); } Dictionary <int, char> dic = new Dictionary <int, char>(); WordsLibrary.ItemTree p = Library; List <int> indexs = new List <int>(); for (int i = 0, j = 0; j < text.Length; j++) { char cha = text[j]; var child = p.Child; var node = child.Find(e => e.Item == cha); if (node != null) { indexs.Add(j); if (node.IsEnd || node.Child == null) { if (node.Child != null) { int k = j + 1; if (k < text.Length && node.Child.Exists(e => e.Item == text[k])) { p = node; continue; } } foreach (var item in indexs) { dic.Add(item, text[item]); } indexs.Clear(); p = Library; i = j; ++i; } else { p = node; } } else { indexs.Clear(); if (p.GetHashCode() != Library.GetHashCode()) { j = i; ++i; p = Library; } else { i = j; } } } return(dic); }