用golang写了敏感词过滤的工具,主要用来检测用户昵称中是否存在敏感词,同时提供剔除转移字符的功能。
可以先将敏感词库存放在一个map中,敏感词可以参考这里:https://github.com/fwwdn/sensitive-stop-words
将map和昵称传入,程序会检查昵称的每一个子串,判断是否在map敏感词库中。复杂度O(len(name)^2)
package util
import (
\"github.com/pkg/errors\"
\"strings\"
)
type filter struct {
data string
maxLimitLen int
}
func NewKeywordFilter(str string, maxLimitLen int) (*filter, error) {
if len(str) > maxLimitLen {
return nil, errors.Errorf(\"长度:%d,不能超过:%d\", len(str), maxLimitLen)
}
return &filter{
data: str,
maxLimitLen: maxLimitLen,
}, nil
}
func (f *filter) GetData() string {
return f.data
}
func (f *filter) FilterKeywords(keywords map[string]bool) (err error) {
if keywords == nil {
return
}
for i := 0; i < len(f.data); i++ {
for j := i + 1; j <= len(f.data); j++ {
subStr := f.data[i:j]
if _, found := keywords[subStr]; found {
err = errors.Errorf(\"昵称违规,建议修改\")
}
}
}
return
}
func (f *filter) TrimAllCharset(ch []string) (err error) {
if ch == nil {
return
}
for _, c := range ch {
f.data = strings.Replace(f.data, c, \"\", -1)
}
if len(f.data) == 0 {
err = errors.New(\"剔除相关转移字符后,数据长度为0.\")
return
}
return
}
继续阅读与本文标签相同的文章
上一篇 :
中科大的黑科技:简单几笔素描就能复原真实人脸
下一篇 :
快看!智能水表这些小知识你需要知道
-
特斯拉自动驾驶系统涨价遭质疑 马斯克:我们不能一直亏钱
2026-05-14栏目: 教程
-
首个二类资源区平价光伏电站正式并网发电
2026-05-14栏目: 教程
-
AI+5G科技创新 视频行业呈现轻应用化趋势
2026-05-14栏目: 教程
-
1.98亿滴滴用户添加了紧急联系人 每天百万个订单行程分享给亲友
2026-05-14栏目: 教程
-
工程院院士刘韵洁:5G前景很大,但主要是行业应用
2026-05-14栏目: 教程
