基于C#實現(xiàn)的敏感字檢測示例
這是今天提到的一個需求,于是做了一個小demo。把過程記錄下來。
第一步 新建項目
比如 demo1 這里是用網(wǎng)站形式
第二步下載敏感詞類庫ToolGood.Words.dll
方案一 可以先去網(wǎng)絡搜索,查找開源的代碼庫,然后把代碼下載下來,自己編譯。
方案二 用nuget下載
第三步創(chuàng)建測試方法
[HttpPost] public ActionResult GetTestMinGan(ProductInfo model) { // 創(chuàng)建敏感詞過濾器對象 var filter = new WordsSearch(); // 添加敏感詞 List<string> words = new List<string>() { "磁性", "帶電", "液體", "膏狀", "粉末", "顆粒", "食品", "仿牌", "電子", "氣體", "動物", "植物", "鮮活類物品", "酒精類", "槍械形狀物品", "貨幣", "金融票據(jù)", "腐蝕品", "藥品類", "毒品", "煙草", "危險物品", "易燃易爆" }; filter.SetKeywords(words); // 檢測文本是否包含敏感詞 string text = model.ProductName; bool containsSensitiveWords = filter.ContainsAny(text); // 輸出結(jié)果 if (containsSensitiveWords) { return Content("文本中包含敏感詞"); } else { return Content("文本中不包含敏感詞"); } }
實體類 ProductInfo
public class ProductInfo { public string ProductName{get;set;} }
第四步測試
其他
這是gpt平臺回答的 ToolGood.Words 是一個C#的敏感詞過濾庫,可以用于快速判斷一段文本中是否包含敏感詞。以下是引入和使用 ToolGood.Words 的示例代碼:
using System; using System.Collections.Generic; using System.Linq; using ToolGood.Words; class Program { static void Main() { // 創(chuàng)建敏感詞過濾器對象 var filter = new WordsSearch(); // 添加敏感詞 List<string> words = new List<string>() { "敏感詞1", "敏感詞2", "敏感詞3" }; filter.SetKeywords(words); // 檢測文本是否包含敏感詞 string text = "這是一段包含敏感詞1和敏感詞2的文本"; bool containsSensitiveWords = filter.ContainsAny(text); // 輸出結(jié)果 if (containsSensitiveWords) { Console.WriteLine("文本中包含敏感詞"); } else { Console.WriteLine("文本中不包含敏感詞"); } } }
以上代碼中,我們首先創(chuàng)建了一個 WordsSearch
對象,這個對象代表一個敏感詞過濾器。然后,我們使用 SetKeywords()
方法給敏感詞過濾器添加敏感詞。
接著,我們定義了一段文本 text
。使用 ContainsAny()
方法檢測這段文本中是否包含任意一個敏感詞。如果包含敏感詞,則輸出 "文本中包含敏感詞",否則輸出 "文本中不包含敏感詞"。
當然,還有許多其它方法可以實現(xiàn)自定義敏感詞庫、檢測詳細的敏感詞信息等功能。你可以根據(jù)具體需求查看 ToolGood.Words 的文檔來使用它提供的功能。
總結(jié)
這個庫使用起來是非常簡單的。關(guān)于敏感詞存放位置。這個根據(jù)需求來,既可以是文件,也可以是數(shù)據(jù)庫,當然也可以寫死在代碼里。根據(jù)自己的需求來。
到此這篇關(guān)于基于C#實現(xiàn)的敏感字檢測示例的文章就介紹到這了,更多相關(guān)C#敏感字檢測內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
深入分析C#連接Oracle數(shù)據(jù)庫的連接字符串詳解
本篇文章是對C#連接Oracle數(shù)據(jù)庫的連接字符串進行了詳細的分析介紹,需要的朋友參考下2013-05-05