[英]How to filter richtextbox from bad words?
我想知道如何在文本更改事件中从坏词中自动过滤richtextbox
。 我正在通过使用 ip 在计算机之间创建连接来开发本地聊天软件,但我需要对其进行过滤,例如
Richtextbox.text = "oh s***";
Richtextbox
会弹出一个消息框提醒用户并禁用输入 5 秒,然后再次启用它。
有趣的问题! 我想,是这样的:
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);
...
}
}
我认为这个问题有点宽泛,但你可以使用 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
。
然后,您可以使用文本替换将有问题的单词替换为经过审查的替换。
问题在于,以这种方式进行审查并没有考虑到baddy中的bad一词。 您可能希望允许baddy ,但不是bad ,但由于这是在文本更改事件处理程序中发生的,因此您将永远无法键入baddy 。
更好的解决方案是在发送文本后对其进行审查,寻找单词边界,修剪标点符号,忽略大小写并检查整个单词是否匹配。
只需要将它实现到我的项目中,以为我会分享我的代码。 我创建了一个文本文件并将其存储在网站中,因此可以轻松修改它而无需重新编译或更改 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 方法 - 你也可以把它放到你的按钮提交事件中
[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;
}
全局.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;
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.