基于C#检测敏感词功能

 更新时间:2024年11月08日 15:18:11   作者:Lazy龙  
这篇文章主要为大家详细介绍了如何基于C#实现检测敏感词功能,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下

今天策划给我一个任务  ——  检测昵称中是否含有敏感词功能,然后丢给我两个压缩包,我解压一看:

有的txt文件是一行一个词:

有的txt文件是按逗号分隔开:

不管是什么格式的总之量非常多,把我这辈子脏话都囊括了

读取TXT文件数据

然后我得先对这些txt文件进行处理转换成我们能用的格式:一开始我直接for循环查找是否含有敏感词,后边找资料看到一个DFA算法。

using System;
using System.Text;
using System.Collections.Generic;
using System.IO;
 
public class Program
{
    static void Main()
    {
        //换行的txt文件
        List<string> list = LineFeed();
        //带有逗号的txt文件
        Comma();
 
        string name = "假如这是敏感词";
 
        //检测昵称中是否含有敏感词
        CensorText(name, list);
 
        Console.Read();
    }
 
    static void CensorText(string text, List<string> list)
    {
        foreach (string line in list)
        {
            if (text.Contains(line))
            {
                Console.WriteLine("昵称中存在无法使用的字符,请修改后再次确认");
            }
        }
    }
 
    //用换行分割的txt文件
    static List<string> LineFeed() 
    {
        string filePath = "E:\\C#Project\\PBZ\\反动词库.txt"; // 替换为你的 txt 文件路径
        List<string> lines = ReadTxtFile(filePath);
 
        string a = "";
        foreach (string line in lines)
        {
            a += "\"" + line + "\",";
 
        }
        Console.WriteLine(a);
        return lines;
    }
 
    static List<string> ReadTxtFile(string filePath)
    {
        List<string> lines = new List<string>();
 
        try
        {
            using (StreamReader sr = new StreamReader(filePath))
            {
                string line;
                while ((line = sr.ReadLine()) != null)
                {
                    lines.Add(line);
                }
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("读取文件时出现错误: " + e.Message);
        }
 
        return lines;
    }
 
    //用逗号分隔的txt文件
    static void Comma() 
    {
        string filePath = "E:\\C#Project\\PBZ\\GFW补充词库.txt"; // 替换为你的 txt 文件路径
        List<string> elements = ReadTxtFile1(filePath);
 
        string a = "";
        foreach (string element in elements)
        {
            a += "\"" + element + "\",";
        }
        Console.WriteLine(a);
    }
 
    static List<string> ReadTxtFile1(string filePath)
    {
        List<string> elements = new List<string>();
 
        try
        {
            using (StreamReader sr = new StreamReader(filePath))
            {
                string line = sr.ReadLine();
                if (line != null)
                {
                    string[] splitElements = line.Split(',');
                    foreach (string element in splitElements)
                    {
                        elements.Add(element);
                    }
                }
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("读取文件时出现错误: " + e.Message);
        }
 
        return elements;
    }
}

这样处理过后的数据就是List<string>,或者可以处理成数组、集合都可以 

我把处理出来的数据放在HashSet中

/// <summary>
/// 敏感词词库
/// </summary>
public static HashSet<string> MaskWord = new HashSet<string>
{
   "敏感词1","敏感词2","敏感词3","..."
}

C#版DFA算法

然后通过C#版的DFA算法判断昵称中是否含有敏感词返回bool型放在工具类中使用:

java实现敏感词过滤(DFA算法)

敏感词管理(DFA算法实现)

/// <summary>
/// 检测敏感词
/// </summary>
/// <param name="text">要检测的词</param>
/// <param name="MaskWord">敏感词词库</param>
/// <returns></returns>
public static bool CheckSensitiveWords(string text)
{
	Dictionary<string, Dictionary<string, string>> stateMap = new Dictionary<string, Dictionary<string, string>>();
	Dictionary<string, string> currentState = new Dictionary<string, string>();
	char[] chars;
 
	foreach (string word in MaskWord)
	{
		currentState = stateMap.ContainsKey("0") ? stateMap["0"] : new Dictionary<string, string>();
		Dictionary<string, string> nextState;
		chars = word.ToCharArray();
		for (int i = 0; i < chars.Length; i++)
		{
			string c = chars[i].ToString();
			string nextStateKey = i == chars.Length - 1 ? "end" : (i + 1).ToString();
			if (currentState.ContainsKey(c))
			{
				nextState = stateMap[currentState[c]];
			}
			else
			{
				nextState = new Dictionary<string, string>();
				stateMap[currentState.Count.ToString()] = nextState;
				currentState[c] = currentState.Count.ToString();
			}
				currentState = nextState;
				currentState["end"] = "end";
		}
	}
 
	currentState = stateMap.ContainsKey("0") ? stateMap["0"] : new Dictionary<string, string>();
	chars = text.ToCharArray();
	for (int i = 0; i < chars.Length; i++)
	{
		string c = chars[i].ToString();
		if (currentState.ContainsKey(c))
		{
			currentState = stateMap[currentState[c]];
			if (currentState.ContainsKey("end"))
			{
				return true; // 匹配到敏感词
			}
		}
		else
		{
			currentState = stateMap.ContainsKey("0") ? stateMap["0"] : new Dictionary<string, string>();
		}
	}
	return false; // 未匹配到敏感词
}

到此这篇关于基于C#检测敏感词功能的文章就介绍到这了,更多相关C#检测敏感词内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • c# 实现控件(ocx)中的事件详解

    c# 实现控件(ocx)中的事件详解

    这篇文章主要介绍了c# 实现控件(ocx)中的事件详解,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-12-12
  • C#中的ICustomFormatter及IFormatProvider接口用法揭秘

    C#中的ICustomFormatter及IFormatProvider接口用法揭秘

    这篇文章主要介绍了C#中的ICustomFormatter及IFormatProvider接口用法揭秘,本文能过分析一段代码得出一些研究结果,需要的朋友可以参考下
    2015-06-06
  • DevExpress之ChartControl的SeriesTemplate实例

    DevExpress之ChartControl的SeriesTemplate实例

    这篇文章主要介绍了DevExpress之ChartControl的SeriesTemplate用法实例,实现了饼状Series百分比显示的效果,具有一定的参考借鉴价值,需要的朋友可以参考下
    2014-10-10
  • c# rsa加密解密详解

    c# rsa加密解密详解

    这篇文章主要介绍了c# rsa加密解密的的相关资料,文中代码非常细致,帮助大家更好的理解和学习,感兴趣的朋友可以了解下
    2020-06-06
  • C#开发webService接口的流程步骤

    C#开发webService接口的流程步骤

    在C#中,Web Service 接口是一种用于远程程序间的通信机制,它允许客户端通过HTTP协议访问服务器端提供的功能和服务,本文给大家详细介绍了C#开发webService接口的流程步骤,需要的朋友可以参考下
    2024-11-11
  • C#实现chart控件动态曲线绘制

    C#实现chart控件动态曲线绘制

    这篇文章主要为大家详细介绍了C#实现chart控件动态曲线绘制,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-02-02
  • C# wpf 无边框窗口添加阴影效果的实现

    C# wpf 无边框窗口添加阴影效果的实现

    在本篇内容中小编给大家整理了一篇关于C# wpf 无边框窗口添加阴影效果的具体方法内容,有兴趣的朋友们可以学习参考下
    2022-11-11
  • C#实现SMTP服务发送邮件的示例代码

    C#实现SMTP服务发送邮件的示例代码

    这篇文章主要为大家详细介绍了如何利用C#实现SMTP服务发送邮件的功能,文中的示例代码讲解详细,对我们学习C#有一定的帮助,感兴趣的小伙伴可以跟随小编一起了解一下
    2022-12-12
  • C# Winform实现石头剪刀布游戏

    C# Winform实现石头剪刀布游戏

    这篇文章主要为大家详细介绍了Winform实现石头剪刀布游戏,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2019-01-01
  • C# Unicode编码解码的实现

    C# Unicode编码解码的实现

    本文主要介绍了C# Unicode编码解码的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2022-06-06

最新评论