【问题标题】:How to filter richtextbox from bad words?如何从坏词中过滤richtextbox?
【发布时间】:2015-09-01 14:57:07
【问题描述】:

我想知道如何从文本更改事件中的坏词中自动过滤richtextbox。我正在开发一个本地聊天软件,通过使用 ip 在计算机之间建立连接,但我需要对其进行过滤,例如

Richtextbox.text = "oh s***";

Richtextbox会弹出一个消息框提醒用户并禁用输入5秒,然后再次启用。

【问题讨论】:

  • 这是StackOverflow,你试过什么?
  • 编辑您的帖子以显示您的代码,不要将其作为评论发布。也就是说,只需编译一个不允许使用的单词列表,并可能将您的文本框拆分为一个空格,看看它是否包含任何不好的内容。
  • 我在手机上我不能:(
  • 你能编辑一下吗:)
  • 该条件永远不会计算为真。您正在将一个值与其自身进行比较,然后在其上附加一些东西——更改该值。他们永远不会一样。

标签: c# .net


【解决方案1】:

有趣的问题!我猜是这样的:

  using System.Text.RegularExpressions;

  ...
  HashSet<String> badWords = new HashSet<string>(StringComparer.OrdinalIgnoreCase) {
    "bad",
    "words",
  };

  Boolean result = YourRichTextBox
    .Lines
    .Any(line => Regex
       .Split(line, @"\W")
       .Any(word => badWords.Contains(word)));

请注意,坏词可以以大写字母、大写字母等开头。另一个困难是我们必须检测"BAD!",而不是"baddy"

提醒用户只需将代码放入TextChanged事件处理中:

  private void YourRichTextBox_TextChanged(object sender, EventArgs e) {
    RichTextBox YourRichTextBox = sender as RichTextBox;

    Boolean result = ... // See code above

    if (result) {
      MessageBox.Show("You must not be that rude!", Text, MessageBoxButtons.OK);
      ...
    }
  }

【讨论】:

  • 我在这一行出现错误 ...Boolean result = YourRichTextBox .Lines .Any(line => line .Regex.Split(line, @"\w") .Any(word => badWords .Contains(word)));
  • @Ahmed Tammaa:将using System.Text.RegularExpressions; 添加到其他人usings
  • 如果用户使用坏词,如何弹出消息框的警报在哪里,请为我的问题投票
  • ,,错误仍然在没有解决抱歉:(你能帮忙吗?
  • @Ahmed Tammaa:我的 2010 VS 副本(不过我有终极版)编译了代码。在其他usings 中有using System.Linq;
【解决方案2】:
  1. 将禁用词放入db,程序启动时缓存。
    • 为了测试,你硬编码了一些单词。
  2. 因为这是一个字符串匹配问题。我建议使用 System.Text.RegularExpressions.Regex 类,希望下面的链接示例代码能给你一些帮助: https://msdn.microsoft.com/en-us/library/ms228595.aspx

【讨论】:

    【解决方案3】:

    我认为这个问题有点宽泛,但您可能可以使用 Linq 做到这一点:

    List<string> badWords = new List<string> { "bad", "words", "here" };
    
    string myString = "This string contains a bad word";
    
    bool badWordInString = badWords.Any(myString.Contains);
    

    如果myString 包含列表中的任何坏词,则badWordInString 将是true

    然后,您可以使用文本替换将有问题的单词替换为经过审查的替换。

    问题在于,以这种方式进行审查是因为它没有考虑到诸如 bad 一词在 baddy 中的情况。您可能希望允许 baddy,但不允许 bad,但由于这是发生在 text changed 事件处理程序中,因此您将永远无法键入 baddy .

    更好的解决方案是在发送文本之后对其进行审查,查找单词边界,修剪标点符号,忽略大小写并检查整个单词是否匹配。

    【讨论】:

    • 我检查请等待结果:)
    • 需要更多说明在哪里发布此代码,在 Richtextbox 中或创建 linq 查询
    • 自从我回答后您已经编辑了问题,所以我需要更新它以进行过滤。这只会让您知道字符串中是否有坏词。
    • @AhmedTammaa,可能在 textchanged 事件中有此代码。
    • 是的,在文本更改事件中。用Richtextbox.Text 切换出myString
    【解决方案4】:

    只需将其实现到我的项目中,我想我会分享我的代码。我创建了一个文本文件并将其存储在网站中,因此可以轻松修改它而无需重新编译或更改 web.config 设置。

    执行此操作的一个好方法是在按钮提交上执行此操作,因为您使用的是 RTE。我会说使用 ajax 在按钮提交之前检查它是否包含“坏词”,这样您就不必进行回发,但看起来您正在使用 Win Forms,这就是 MVC。但是你可以得到图片。

    我在这个网站https://github.com/shutterstock/List-of-Dirty-Naughty-Obscene-and-Otherwise-Bad-Words使用了英语和西班牙语的“坏词”

    文本文件放在 /Content 文件夹中(在我的情况下)

    这里是 ajax,如果你可以使用(或者如果其他人想要的话)

    $('#form-ID').on('click', 'button[type="submit"]', function (e) {
        var badWords = '',
            str = $('#form-ID').find('textarea').val();
    
        $.ajax({
            url: '/YourAPI/CheckForBadWords?str=' + str,
            type: 'POST',
            dataType: 'json',
            data: '',
            async: false,
            contentType: 'application/json; charset=utf-8',
            complete: function (data) {
                badWords = data.responseText;
            }
        });
    
        if (badWords != '') {
            console.log('oh no --- ' + badWords)
            e.preventDefault();
            return false;
        }     
    });
    

    Api 方法 - 您也可以将其放入您的 Button 提交事件中

     [HttpPost] // <--- remove if not using Api
     public string CheckForBadWords(string str)
     {
         string badWords = string.Empty;
         var badWordsResult = Global.CheckForBadWords(str);
         if (badWordsResult.Length > 0)
         {
             badWords = string.Join(", ", badWordsResult);
         }
    
         return badWords;
     }
    

    Global.cs 文件

    public static class Global 
    {
            /// <summary>
            /// Returns a list of bad words found in the string based
            /// on spanish and english "bad words"
            /// </summary>
            /// <param name="str">the string to check</param>
            /// <returns>list of bad words found in string (if any)</returns>
            public static string[] CheckForBadWords(string str)
            {
                var badWords = GetBadWords();
                var badWordsCaught = new List<string>();
    
                if (badWords.Any(str.ToLower().Contains))
                {
                    badWordsCaught = badWords.Where(x => str.Contains(x)).ToList();
                }
    
                return badWordsCaught.ToArray();
            }
    
        /// <summary>
        /// Retrieves a list of "bad words" from the text file. Words include
        /// both spanish and english
        /// </summary>
        /// <returns>strings of bad words</returns>
        private static List<string> GetBadWords()
        {
            var badWords = new List<string>();
            string fileName = string.Format("{0}/Content/InvalidWords.txt", AppDomain.CurrentDomain.BaseDirectory);
            if (System.IO.File.Exists(fileName))
            {
                badWords = System.IO.File.ReadAllLines(fileName).ToList();
            }
    
            return badWords.ConvertAll(x => x.ToLower());
        }
    }
    

    编辑:

    必须从 URL 字符限制的 api 调用 b/c 中删除查询字符串参数。相反,我只是传递 JSON 字符串

    var badWords = '',
        str = stringHERE;
    
    $.ajax({
        url: '/YourApiController/CheckForBadWords',
        type: 'POST',
        dataType: 'json',
        data: JSON.stringify({ str: str }),
        async: false,
        contentType: 'application/json; charset=utf-8',
        complete: function (data) {
            badWords = data.responseText;
        }
    });
    

    【讨论】:

    猜你喜欢
    • 2018-10-17
    • 1970-01-01
    • 1970-01-01
    • 2021-06-14
    • 2022-10-24
    • 2012-07-24
    • 1970-01-01
    • 1970-01-01
    • 2019-01-11
    相关资源
    最近更新 更多