C# 实现敏感词过滤
实现 该 敏感词过滤 采用的是 DFA算法,参考文章:https://blog.csdn.net/chenssy/article/details/26961957
具体 实现 步骤 如下:
第一步,构建 敏感词库(WordsLibrary) 类:
using System.Collections.Generic;
using System.Linq;
using System; namespace ContentSafe.SensitiveWord
{
/// <summary>
/// 敏感词库
/// </summary>
public class WordsLibrary
{
/// <summary>
/// 词库树结构类
/// </summary>
public class ItemTree
{
public char Item { get; set; }
public bool IsEnd { get; set; }
public List<ItemTree> Child { get; set; }
} /// <summary>
/// 词库树
/// </summary>
public ItemTree Library { get; private set; } /// <summary>
/// 敏感词组
/// </summary>
public string[] Words { get; protected set; } /// <summary>
/// 敏感词库
/// </summary>
public WordsLibrary()
{
LoadWords();
Init();
} /// <summary>
/// 敏感词库
/// </summary>
/// <param name="words">敏感词组</param>
public WordsLibrary(string[] words) : this()
{
Words = words;
} /// <summary>
/// 加载 敏感词组,可被重写以自定义 如何加载 敏感词组
/// </summary>
public virtual void LoadWords()
{
} /// <summary>
/// 词库初始化
/// </summary>
private void Init()
{
if (Words == null)
Words = new[] { "" }; Library = new ItemTree() { Item = 'R', IsEnd = false, Child = CreateTree(Words) };
} /// <summary>
/// 创建词库树
/// </summary>
/// <param name="words">敏感词组</param>
/// <returns></returns>
private List<ItemTree> CreateTree(string[] words)
{
List<ItemTree> tree = null; if (words != null && words.Length > )
{
tree = new List<ItemTree>(); foreach (var item in words)
if (!string.IsNullOrEmpty(item))
{
char cha = item[]; ItemTree node = tree.Find(e => e.Item == cha);
if (node != null)
AddChildTree(node, item);
else
tree.Add(CreateSingleTree(item));
}
} return tree;
} /// <summary>
/// 创建单个完整树
/// </summary>
/// <param name="word">单个敏感词</param>
/// <returns></returns>
private ItemTree CreateSingleTree(string word)
{
//根节点,此节点 值为空
ItemTree root = new ItemTree();
//移动 游标
ItemTree p = root; for (int i = ; i < word.Length; i++)
{
ItemTree child = new ItemTree() { Item = word[i], IsEnd = false, Child = null };
p.Child = new List<ItemTree>() { child };
p = child;
}
p.IsEnd = true; return root.Child.First();
} /// <summary>
/// 附加分支子树
/// </summary>
/// <param name="childTree">子树</param>
/// <param name="word">单个敏感词</param>
private void AddChildTree(ItemTree childTree, string word)
{
//移动 游标
ItemTree p = childTree; for (int i = ; i < word.Length; i++)
{
char cha = word[i];
List<ItemTree> child = p.Child; if (child == null)
{
ItemTree node = new ItemTree() { Item = cha, IsEnd = false, Child = null };
p.Child = new List<ItemTree>() { node };
p = node;
}
else
{
ItemTree node = child.Find(e => e.Item == cha);
if (node == null)
{
node = new ItemTree() { Item = cha, IsEnd = false, Child = null };
child.Add(node);
p = node;
}
else
p = node;
}
}
p.IsEnd = true;
}
}
}
第二步,构建 敏感词检测(ContentCheck) 类:
using System.Collections.Generic;
using System.Linq;
using System; namespace ContentSafe.SensitiveWord
{
/// <summary>
/// 敏感词检测
/// </summary>
public class ContentCheck
{
/// <summary>
/// 检测文本
/// </summary>
public string Text { private get; set; } /// <summary>
/// 敏感词库 词树
/// </summary>
public WordsLibrary.ItemTree Library { private get; set; } /// <summary>
/// 敏感词检测
/// </summary>
public ContentCheck() { } /// <summary>
/// 敏感词检测
/// </summary>
/// <param name="library">敏感词库</param>
public ContentCheck(WordsLibrary library)
{
if (library.Library == null)
throw new Exception("敏感词库未初始化"); Library = library.Library;
} /// <summary>
/// 敏感词检测
/// </summary>
/// <param name="library">敏感词库</param>
/// <param name="text">检测文本</param>
public ContentCheck(WordsLibrary library, string text) : this(library)
{
if (text == null)
throw new Exception("检测文本不能为null"); Text = text;
} /// <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 = , j = ; 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 + ;
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())
{
++i;
j = i;
p = Library;
}
else
i = j;
}
} return dic;
} /// <summary>
/// 替换敏感词
/// </summary>
/// <param name="library">敏感词库</param>
/// <param name="text">检测文本</param>
/// <param name="newChar">替换字符</param>
/// <returns></returns>
public static string SensitiveWordsReplace(WordsLibrary library, string text, char newChar = '*')
{
Dictionary<int, char> dic = new ContentCheck(library).WordsCheck(text);
if (dic != null && dic.Keys.Count > )
{
char[] chars = text.ToCharArray();
foreach (var item in dic)
chars[item.Key] = newChar; text = new string(chars);
} return text;
} /// <summary>
/// 替换敏感词
/// </summary>
/// <param name="text">检测文本</param>
/// <param name="newChar">替换字符</param>
/// <returns></returns>
public string SensitiveWordsReplace(string text, char newChar = '*')
{
Dictionary<int, char> dic = WordsCheck(text);
if (dic != null && dic.Keys.Count > )
{
char[] chars = text.ToCharArray();
foreach (var item in dic)
chars[item.Key] = newChar; text = new string(chars);
} return text;
} /// <summary>
/// 替换敏感词
/// </summary>
/// <param name="newChar">替换字符</param>
/// <returns></returns>
public string SensitiveWordsReplace(char newChar = '*')
{
if (Text == null)
throw new Exception("未设置检测文本"); return SensitiveWordsReplace(Text, newChar);
} /// <summary>
/// 查找敏感词
/// </summary>
/// <param name="library">敏感词库</param>
/// <param name="text">检测文本</param>
/// <returns></returns>
public static List<string> FindSensitiveWords(WordsLibrary library, string text)
{
ContentCheck check = new ContentCheck(library, text);
return check.FindSensitiveWords();
} /// <summary>
/// 查找敏感词
/// </summary>
/// <param name="text">检测文本</param>
/// <returns></returns>
public List<string> FindSensitiveWords(string text)
{
Dictionary<int, char> dic = WordsCheck(text);
if (dic != null && dic.Keys.Count > )
{
int i = -;
string str = "";
List<string> list = new List<string>();
foreach(var item in dic)
{
if (i == - || i + == item.Key)
str += item.Value;
else
{
list.Add(str);
str = "" + item.Value;
} i = item.Key;
}
list.Add(str); return list.Distinct().ToList();
}
else
return null;
} /// <summary>
/// 查找敏感词
/// </summary>
/// <returns></returns>
public List<string> FindSensitiveWords()
{
if (Text == null)
throw new Exception("未设置检测文本"); return FindSensitiveWords(Text);
}
}
}
第三步,测试与使用方法:
string[] words = new[] { "敏感词1", "敏感词2", "含有", "垃圾" }; //敏感词组 可自行在网上 搜索下载
//敏感词库 类可被继承,如果想实现自定义 敏感词导入方法 可以 对 LoadWords 方法进行 重写
var library = new WordsLibrary(words); //实例化 敏感词库
string text = "在任意一个文本中都可能包含敏感词1、2、3等等,只要含有敏感词都会被找出来,比如:垃圾";
ContentCheck check = new ContentCheck(library, text); //实例化 内容检测类
var list = check.FindSensitiveWords(); //调用 查找敏感词方法 返回敏感词列表
var str = check.SensitiveWordsReplace(); //调用 敏感词替换方法 返回处理过的字符串
该 实现方案 不止 这个 使用方法,更多使用方法 可自行 研究
C# 实现敏感词过滤的更多相关文章
- java实现敏感词过滤(DFA算法)
小Alan在最近的开发中遇到了敏感词过滤,便去网上查阅了很多敏感词过滤的资料,在这里也和大家分享一下自己的理解. 敏感词过滤应该是不用给大家过多的解释吧?讲白了就是你在项目中输入某些字(比如输入xxo ...
- 用php实现一个敏感词过滤功能
周末空余时间撸了一个敏感词过滤功能,下边记录下实现过程. 敏感词,一方面是你懂的,另一方面是我们自己可能也要过滤一些人身攻击或者广告信息等,具体词库可以google下,有很多. 过滤敏感词,使用简单的 ...
- 浅析敏感词过滤算法(C++)
为了提高查找效率,这里将敏感词用树形结构存储,每个节点有一个map成员,其映射关系为一个string对应一个TreeNode. STL::map是按照operator<比较判断元素是否相同,以及 ...
- Java实现敏感词过滤
敏感词.文字过滤是一个网站必不可少的功能,如何设计一个好的.高效的过滤算法是非常有必要的.前段时间我一个朋友(马上毕业,接触编程不久)要我帮他看一个文字过滤的东西,它说检索效率非常慢.我把它程序拿过来 ...
- php敏感词过滤
在项目开发中发现有个同事在做敏感词过滤的时候用循环在判断,其实是不用这样做的,用php的数组函数和字符串函数即可实现 function filterNGWords($string) { $badwor ...
- 转:鏖战双十一-阿里直播平台面临的技术挑战(webSocket, 敏感词过滤等很不错)
转自:http://www.infoq.com/cn/articles/alibaba-broadcast-platform-technology-challenges 鏖战双十一-阿里直播平台面临的 ...
- java敏感词过滤
敏感词过滤在网站开发必不可少.一般用DFA,这种比较好的算法实现的. 参考链接:http://cmsblogs.com/?p=1031 一个比较好的代码实现: import java.io.IOExc ...
- Java实现敏感词过滤(转)
敏感词.文字过滤是一个网站必不可少的功能,如何设计一个好的.高效的过滤算法是非常有必要的.前段时间我一个朋友(马上毕业,接触编程不久)要我帮他看一个文字过滤的东西,它说检索效率非常慢.我把它程序拿过来 ...
- DFA和trie特里实现敏感词过滤(python和c语言)
今天的项目是与完成python开展,需要使用做关键词检查,筛选分类,使用前c语言做这种事情.有了线索,非常高效,内存小了,检查快. 到达python在,第一个想法是pip基于外观的c语言python特 ...
- Jsp敏感词过滤
Jsp敏感词过滤 大部分论坛.网站等,为了方便管理,都进行了关于敏感词的设定. 在多数网站,敏感词一般是指带有敏感政治倾向(或反执政党倾向).暴力倾向.不健康色彩的词或不文明语,也有一些网站根据自身实 ...
随机推荐
- MySQL学习——操作数据库
MySQL学习——操作数据库 摘要:本文主要学习了使用DDL语句操作数据库的方法. 创建数据库 语法 create database [if not exists] 数据库名 [default] ch ...
- MySqlBulkLoader 中文乱码
MySQL驱动:MySqlConnector GitHub地址:https://github.com/mysql-net/MySqlConnector.git 文档地址:https://mysql-n ...
- Android多module下重复jar包问题
版权声明:本文为xing_star原创文章,转载请注明出处! 本文同步自http://javaexception.com/archives/166 Android多module下重复jar包问题 An ...
- UML类图和用例图
软件体系结构的多视图 kruchten提出了软件体系结构的4+1视图模型,其中用例图位于中心位置(4+1视图中的1). 逻辑视图 一种静态建模视图 进程视图 一种并发进程或任务视图 开发视 ...
- impdp中的DISABLE_ARCHIVE_LOGGING参数测试
impdp中的DISABLE_ARCHIVE_LOGGING参数测试 发表于 2017 年 04 月 08 日 由 惜分飞 联系:手机/微信(+86 13429648788) QQ(107644445 ...
- windows双网卡绑定
windows双网卡绑定 开门贱山: 以下内容纯属抄袭,如有雷同,也是醉了~~!! ————————————— ...
- Python—闭包和装饰器
闭包 定义:内部函数对外部函数变量的引用,则将该函数与用到的变量称为闭包. 闭包必须满足以下三个条件: 必须有一个内嵌函数. 内嵌函数必须引用外部函数中的变量. 外部函数返回值必须是内嵌函数的引用. ...
- Mybatis-plus中的常用注解
@TableName:数据库表相关 @TableId:表主键标识 @TableField:表字段标识 @TableLogic:表字段逻辑处理注解(逻辑删除) @TableId(type= IdType ...
- c# WF 第3节 窗体的属性
本节内容: 1:如何找到窗口属性 2:窗口属性 1:如何找到窗口属性 2:窗口属性
- class 命名规范(三)
抄自:https://www.jianshu.com/p/4945d9cf14e5 一.常见class关键词 布局类:header, footer, container, main, content, ...