微信公众号“DotNet”看到介绍.net开源敏感词检测库ToolGood.Words的文章《.NET Core一款高性能敏感词检测开源库》,根据参考文献2中的测试,该库的检测效率比C#自带的正则效率高8.8倍,如果数量量越大性能优势越明显。
ToolGood.Words的GitHub地址见参考文献1,除了支持非法词(敏感词)检测,其还支持繁体简体互换、全角半角互换、获取拼音首字母、获取拼音字母、拼音模糊搜索等功能。
本文主要测试其关键词检索功能。
ToolGood.Words库中的StringSearch、StringSearchEx、StringSearchEx2、WordsSearch、WordsSearchEx、WordsSearchEx2、IllegalWordsSearch等类都支持敏感词检测,区别在于String开头的类的检测函数返回值均为字符串类型,而Words开头的类的检测函数返回值为WordsSearchResult ,该类记录匹配检索条件的字符串的起始和结束位置,同时IllegalWordsSearch为过滤非法词(敏感词)专用类,可设置跳字长度,默认全角转半角,忽略大小写,跳词,重复词,黑名单等。
除了固定检索词,上述检测类还支持有限的正则表达式(.(点)?(问号) (|)(括号与竖线))。本文中主要使用WordsSearch类进行敏感词检测测试,该类与WordsSearchEx、WordsSearchEx2相比性能最低,根据参考文献1中的介绍,性能从小到大 WordsSearch < WordsSearchEx < WordsSearchEx2 < WordsSearchEx3。
WordsSearch的重要函数定义如下所示,本文中主要使用FindAll函数获取所有匹配项的具体信息。返回值类型WordsSearchResult的定义如下所示。
public class WordsSearch {// 判断文本是否包含关键字public bool ContainsAny(string text);// 在文本中查找第一个关键字public WordsSearchResult FindFirst(string text);// 在文本中查找所有的关键字public List FindAll(string text);// 在文本中替换所有的关键字public string Replace(string text, char replaceChar = '*');//设置搜索关键字,可为固定字符串,也可为正则表达式public virtual void SetKeywords(ICollection keywords);}public class WordsSearchResult{// 匹配项的开始位置public int Start { get; private set; }// 匹配项的结束位置public int End { get; private set; }// 关键字public string Keyword { get; private set; }// 索引public int Index { get; private set; }// 匹配关键字public string MatchKeyword { get; private set; }}
对照实际的值可以更直观地看出WordsSearchResult的各个属性的意义,如下图所示:
本文的测试思路是加载本地的txt文件,设置多个关键词,然后高亮显示搜索结果,并能在各个搜索项之间切换。主要使用的是WordsSearch的检测功能,同时使用RichTextbox控件的高亮显示及跳转功能。主要代码如下:
//检测并显示检测结果WordsSearch ws = new WordsSearch();ws.SetKeywords(txtResearchWord.Text.Split(';',';'));List results = ws.FindAll(txtContent.Text);for(int i=0;iListViewItem lvi = new ListViewItem(Convert.ToString(i + 1));lvi.SubItems.Add(results[i].MatchKeyword);lvi.SubItems.Add(string.Format("位置:{0}~{1}", results[i].Start, results[i].End));lvi.Tag = results[i];lstResult.Items.Add(lvi);txtContent.Select(results[i].Start, results[i].End-results[i].Start+1);txtContent.SelectionFont = new Font(txtContent.SelectionFont,FontStyle.Underline|FontStyle.Bold);txtContent.SelectionBackColor = Color.LightBlue;}//跳转到选中匹配项WordsSearchResult result = lstResult.SelectedItems[0].Tag as WordsSearchResult;txtContent.SelectionStart = result.Start;txtContent.ScrollToCaret();
测试程序的运行效果如下图所示:
参考文献:
[1]https://github.com/toolgood/ToolGood.Words
[2]https://blog.csdn.net/daremeself/article/details/127522209