C# 實現敏感詞過濾

来源:https://www.cnblogs.com/sgwy/archive/2019/11/08/11821126.html
-Advertisement-
Play Games

實現 該 敏感詞過濾 採用的是 DFA演算法,參考文章:https://blog.csdn.net/chenssy/article/details/26961957 具體 實現 步驟 如下: 第一步,構建 敏感詞庫(WordsLibrary) 類: using System.Collections.G ...


  實現 該 敏感詞過濾 採用的是 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 > 0)
            {
                tree = new List<ItemTree>();

                foreach (var item in words)
                    if (!string.IsNullOrEmpty(item))
                    {
                        char cha = item[0];

                        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 = 0; 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 = 1; 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 = 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())
                    {
                        ++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 > 0)
            {
                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 > 0)
            {
                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 > 0)
            {
                int i = -1;
                string str = "";
                List<string> list = new List<string>();
                foreach(var item in dic)
                {
                    if (i == -1 || i + 1 == 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();  //調用 敏感詞替換方法 返回處理過的字元串

  該 實現方案 不止 這個 使用方法,更多使用方法 可自行 研究


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • php中有很多排序的函數,sort,rsort,ksort,krsort,asort,arsort,natcasesort,這些函數用來對數組的鍵或值進行這樣,或那樣的排序。 可以終究有時候還需要一些函數來隨機獲取數組的元素。 array_rand()函數 隨機獲取數組中的一個函數,可以通過第二個參 ...
  • 前言 最近在做智能家居平臺,考慮到家居的控制需要快速的響應於是打算使用redis緩存。一方面減少資料庫壓力另一方面又能提高響應速度。項目中使用的技術棧基本上都是大家熟悉的springboot全家桶,在springboot2.x以後操作redis的客戶端推薦使用lettuce(生菜)取代jedis。 ...
  • 2019年11月8日,近期做項目開始實行前後端分離的方式開發,前端使用vue的框架,打包發佈後,調用後端介面出現跨域的問題,網上搜索出來的都是以下的配置方式: 但是,在我的項目中,按這種方式配置沒有效果,還會出現跨域的問題,後來發現是前後端請求設置的在Headers裡面傳輸token來進行校驗,那麼 ...
  • 網上看到很多人說 NPOI 的性能不行,自己寫了一個 NPOI 的擴展庫,於是想嘗試看看 NPOI 的性能究竟怎麼樣,道聽途說始終不如自己動手一試。 ...
  • 1. 沒有在Program里配置IIS webBuilder.UseIIS(); 2. StartupProduction 里AutoFac容器註入錯誤和新版的CORS中間件已經阻止使用允許任意Origin,即 AllowAnyOrgin設置了也不會生效 3. 可以嘗試下 在網站根目錄dotnet ...
  • 我是一名 ASP.NET 程式員,專註於 B/S 項目開發。累計文章閱讀量超過一千萬,我的博客主頁地址:https://www.itsvse.com/blog_xzz.html 網上有很多關於npoi讀取excel表格的例子,很多都是返回一個Datatable的對象,但是我需要的是一個list集合, ...
  • 場景 DevExpress的TreeList怎樣設置數據源,從實例入手: https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/102548490 滑鼠雙擊TreeList中的某一節點,在雙擊事件中怎樣獲取當前節點。 註: 博客主頁: h ...
  • 場景 在Winform中進行頁面設計時,常使用控制項的Dock屬性來進行佈局調整。但是由於設置屬性的順序問題,導致達不到想要的效果。 比如以下兩個控制項 下麵的控制項設置的Dock屬性是Bottom,即在頁面底部,那麼再設置上面的控制項的Dock屬性為Fill,理想效果是應該他們按當前佈局顯示在頁面上。但是 ...
一周排行
    -Advertisement-
    Play Games
  • 概述:在C#中,++i和i++都是自增運算符,其中++i先增加值再返回,而i++先返回值再增加。應用場景根據需求選擇,首碼適合先增後用,尾碼適合先用後增。詳細示例提供清晰的代碼演示這兩者的操作時機和實際應用。 在C#中,++i 和 i++ 都是自增運算符,但它們在操作上有細微的差異,主要體現在操作的 ...
  • 上次發佈了:Taurus.MVC 性能壓力測試(ap 壓測 和 linux 下wrk 壓測):.NET Core 版本,今天計劃準備壓測一下 .NET 版本,來測試並記錄一下 Taurus.MVC 框架在 .NET 版本的性能,以便後續持續優化改進。 為了方便對比,本文章的電腦環境和測試思路,儘量和... ...
  • .NET WebAPI作為一種構建RESTful服務的強大工具,為開發者提供了便捷的方式來定義、處理HTTP請求並返迴響應。在設計API介面時,正確地接收和解析客戶端發送的數據至關重要。.NET WebAPI提供了一系列特性,如[FromRoute]、[FromQuery]和[FromBody],用 ...
  • 原因:我之所以想做這個項目,是因為在之前查找關於C#/WPF相關資料時,我發現講解圖像濾鏡的資源非常稀缺。此外,我註意到許多現有的開源庫主要基於CPU進行圖像渲染。這種方式在處理大量圖像時,會導致CPU的渲染負擔過重。因此,我將在下文中介紹如何通過GPU渲染來有效實現圖像的各種濾鏡效果。 生成的效果 ...
  • 引言 上一章我們介紹了在xUnit單元測試中用xUnit.DependencyInject來使用依賴註入,上一章我們的Sample.Repository倉儲層有一個批量註入的介面沒有做單元測試,今天用這個示例來演示一下如何用Bogus創建模擬數據 ,和 EFCore 的種子數據生成 Bogus 的優 ...
  • 一、前言 在自己的項目中,涉及到實時心率曲線的繪製,項目上的曲線繪製,一般很難找到能直接用的第三方庫,而且有些還是定製化的功能,所以還是自己繪製比較方便。很多人一聽到自己畫就害怕,感覺很難,今天就分享一個完整的實時心率數據繪製心率曲線圖的例子;之前的博客也分享給DrawingVisual繪製曲線的方 ...
  • 如果你在自定義的 Main 方法中直接使用 App 類並啟動應用程式,但發現 App.xaml 中定義的資源沒有被正確載入,那麼問題可能在於如何正確配置 App.xaml 與你的 App 類的交互。 確保 App.xaml 文件中的 x:Class 屬性正確指向你的 App 類。這樣,當你創建 Ap ...
  • 一:背景 1. 講故事 上個月有個朋友在微信上找到我,說他們的軟體在客戶那邊隔幾天就要崩潰一次,一直都沒有找到原因,讓我幫忙看下怎麼回事,確實工控類的軟體環境複雜難搞,朋友手上有一個崩潰的dump,剛好丟給我來分析一下。 二:WinDbg分析 1. 程式為什麼會崩潰 windbg 有一個厲害之處在於 ...
  • 前言 .NET生態中有許多依賴註入容器。在大多數情況下,微軟提供的內置容器在易用性和性能方面都非常優秀。外加ASP.NET Core預設使用內置容器,使用很方便。 但是筆者在使用中一直有一個頭疼的問題:服務工廠無法提供請求的服務類型相關的信息。這在一般情況下並沒有影響,但是內置容器支持註冊開放泛型服 ...
  • 一、前言 在項目開發過程中,DataGrid是經常使用到的一個數據展示控制項,而通常表格的最後一列是作為操作列存在,比如會有編輯、刪除等功能按鈕。但WPF的原始DataGrid中,預設只支持固定左側列,這跟大家習慣性操作列放最後不符,今天就來介紹一種簡單的方式實現固定右側列。(這裡的實現方式參考的大佬 ...