场景
在开发博客、留言板、聊天等功能的时候,有些涉及到的敏感词语不能发不出来。这时候我们就要对用户发送的字符串进行过滤,屏蔽掉敏感的字符,用指定的符号进行替代,比如我们在发表文章,留言或者游戏里面聊天的时候,出现的不雅字符都会被“***”替代。下面就来实现这样一个功能。
这里采用Trie 树进行敏感词的一个过滤,本篇文章是基于Trie树这篇文章中的代码基础上进行扩展的。
敏感词过滤
GO版
func (t *Trie) Replace(src string, rep string) string {
node := t.Root
seek := 0
var newRune []rune
var srcRune = []rune(src)
for index, v := range srcRune {
child, ok := node.Child[v]
if !ok {
newRune = append(newRune, srcRune[seek:index+1]...)
seek = index + 1
continue
}
node = child
if node.IsWord {
node = t.Root
newRune = append(newRune, []rune(rep)...)
seek = index + 1
continue
}
}
return string(newRune)
}
调用
func main(){
trie:=NewTrie()
// 添加敏感词词库
trie.Insert("TM")
trie.Insert("王八蛋")
trie.Insert("giao")
// 敏感词过滤
str :=`张三早上出门,突然,天上的掉下一坨鸟屎砸在他脸上,他随口说了一句:TM,今天走了鸟屎运。当他走在马路边的时候,
一辆汽车飞驰而过,此时,路边水洼中的水溅了他一身,他口中骂到:哪个王八蛋,这么不长眼`
str = trie.Replace(str,"***")
fmt.Println(str)
}
效果如下:
img
C#版
// 替换/过滤
public string Replace(string oldStr, string newStr)
{
var node = Root;
var bt = oldStr.ToCharArray();
var sb = new StringBuilder();
for (int i = 0; i < bt.Length; i++)
{
if (!node.Child.ContainsKey(bt[i]))
{
sb.Append(bt[i]);
continue;
}
node = node.Child[bt[i]];
if (node.IsWord)
{
node = Root;
sb.Append(newStr);
continue;
}
}
return sb.ToString();
}
调用
class Program
{
static void Main(string[] args)
{
var trie = new Trie();
// 添加敏感词库
trie.Insert("TM");
trie.Insert("王八蛋");
trie.Insert("giao");
var str = @"张三早上出门,突然,天上的掉下一坨鸟屎砸在他脸上,他随口说了一句:TM,今天走了鸟屎运,giao。当他走在马路边的时候,
一辆汽车飞驰而过,此时,路边水洼中的水溅了他一身,他口中骂到:哪个王八蛋,这么不长眼";
//过滤
str = trie.Replace(str, "***");
Console.WriteLine(str);
}
}
效果如下:
img