-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmoderation.go
96 lines (83 loc) · 2.27 KB
/
moderation.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package moderation
import "strings"
// todo надо бы сравнить бенчмарк с поиском через регулярку
// todo надо полный список матерных слов
var badWords = []string{"хуй", "хуета", "хуев", "пиписьк", "жопа", "срака", "мудак", "мудила", "пизд", "ебать", "ёбнут", "ебнут", "ебстись", "ебанут", "блядь", "шлюх", "блядск", "fuck", "asshole"}
var root *trieNode
func init() {
root = buildTrie(badWords)
buildFailureLinks(root)
}
type trieNode struct {
children map[rune]*trieNode
fail *trieNode
output []string
}
func newTrieNode() *trieNode {
return &trieNode{
children: make(map[rune]*trieNode),
fail: nil,
output: []string{},
}
}
func buildTrie(keywords []string) *trieNode {
result := newTrieNode()
for _, keyword := range keywords {
current := result
for _, char := range keyword {
if _, exists := current.children[char]; !exists {
current.children[char] = newTrieNode()
}
current = current.children[char]
}
current.output = append(current.output, keyword)
}
return result
}
func buildFailureLinks(root *trieNode) {
var queue []*trieNode
for _, child := range root.children {
child.fail = root
queue = append(queue, child)
}
for len(queue) > 0 {
current := queue[0]
queue = queue[1:]
for char, child := range current.children {
queue = append(queue, child)
failState := current.fail
for failState != nil {
if failChild, exists := failState.children[char]; exists {
child.fail = failChild
break
}
failState = failState.fail
}
if child.fail == nil {
child.fail = root
}
child.output = append(child.output, child.fail.output...)
}
}
}
func ahoCorasickSearch(text string, root *trieNode) []string {
var results []string
current := root
for _, char := range text {
for current != nil && current.children[char] == nil {
current = current.fail
}
if current == nil {
current = root
} else {
current = current.children[char]
}
for _, keyword := range current.output {
results = append(results, keyword)
}
}
return results
}
func SearchBadWord(text string) []string {
return ahoCorasickSearch(strings.ToLower(text), root)
}