【Unity】敏感词过滤

下方链接是一个需要过滤的敏感词汇的txt文件,可根据需要自行编辑。

https://files.cnblogs.com/files/weigangblog/SensitiveWords1.zip

这里是将txt文件放在StreamingAssets文件夹中,FilterHelp在启动之后加载使用,使用的时候传入字符内容直接返回过滤结果:

var result = FilterHelp.Instance.FilterWord(content);

下面为FilterHelper类代码:

复制代码
using UnityEngine;
using System.Collections;
public class FilterHelp : MonoBehaviour
{
    private static string[] SentiWords = null; //定义一个接受文件内容的字符串数组
    public static FilterHelp Instance { get; private set; }
    /// <summary>
    /// 使用一个协程来进行文件读取
    /// </summary>
    /// <returns></returns>
    private IEnumerator LoadWWW()
    {
        WWW www;
        //不同平台下StreamingAssets的路径是不同的,这里需要注意一下。
        if (Application.platform == RuntimePlatform.Android)
        {

            www = new WWW(Application.streamingAssetsPath + "/" + "SensitiveWords1.txt");
        }
        else
        {
            www = new WWW("file://" + Application.streamingAssetsPath + "/" + "SensitiveWords1.txt");
        }

        yield return www;

        if (!(www.Equals("") || www.Equals(null)))
        {
            //Debug.Log(www.text);
            //将读取到的字符串进行分割后存储到定义好的数组中
            SentiWords = www.text.Split(',');
        }
    }

    private void Awake()
    {
        Instance = this;
    }

    //在Start()函数中开启协程加载文件
    private void Start()
    {
        StartCoroutine("LoadWWW");
        //添加输入事件监听
        //transform.GetComponent<InputField>().onValueChanged.AddListener(OnValueChanged);
    }

    /// <summary>
    /// 监听方法,该方法会在监测到输入值改变时被触发
    /// </summary>
    /// <param name="t"></param> 参数为当前输入的值
    public bool OnValueChanged(string t)
    {
        if (SentiWords == null)
            return false;
        print("..........");
        foreach (string ssr in SentiWords)
        {
            if (t.Contains(ssr))
            {
                if (!ssr.Equals(""))
                {
                    Debug.Log("包含敏感词汇:" + ssr + ",需要进行替换");
                    return true;
                    //将敏感词替换*
                    //string stt = transform.GetComponent<InputField>().text;
                    //int length = ssr.ToCharArray().Length;
                    //string s = "";
                    //for (int i = 0; i < length; i++)
                    //    s += "*";
                    //Debug.Log(stt.Replace(ssr, s));
                    //stt = stt.Replace(ssr, s);
                    //transform.GetComponent<InputField>().text = stt;
                }
            }

        }

        return false;
    }
}
复制代码

 

posted @   weigang  阅读(846)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示