case-api/api/service/BasicSensitiveWord.go
2025-03-07 16:57:28 +08:00

70 lines
1.4 KiB
Go

package service
import (
"case-api/api/dao"
)
type BasicSensitiveWordService struct {
}
type TrieNode struct {
Children map[rune]*TrieNode
IsEnd bool
}
type Trie struct {
Root *TrieNode
}
func (t *Trie) Insert(word string) {
node := t.Root
for _, ch := range word {
if node.Children[ch] == nil {
node.Children[ch] = &TrieNode{Children: make(map[rune]*TrieNode)}
}
node = node.Children[ch]
}
node.IsEnd = true
}
func (t *Trie) Filter(comment string) (s string, isSensitive int) {
runes := []rune(comment)
n := len(runes)
for i := 0; i < n; i++ {
node := t.Root
j := i
for j < n && node.Children[runes[j]] != nil {
node = node.Children[runes[j]]
j++
if node.IsEnd {
for k := i; k < j; k++ {
runes[k] = '*'
isSensitive = 1
}
break
}
}
}
return string(runes), isSensitive
}
// Filter 过滤敏感词
func (r *BasicSensitiveWordService) Filter(comment string) (s string, isSensitive int) {
basicSensitiveWordDao := dao.BasicSensitiveWordDao{}
maps := make(map[string]interface{})
basicSensitiveWords, _ := basicSensitiveWordDao.GetBasicSensitiveWordList(maps)
if len(basicSensitiveWords) <= 0 {
return comment, isSensitive
}
trie := &Trie{Root: &TrieNode{Children: make(map[rune]*TrieNode)}}
for _, word := range basicSensitiveWords {
trie.Insert(word.Word)
}
comment, isSensitive = trie.Filter(comment)
trie = &Trie{}
return comment, isSensitive
}