-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathsensitive_words.go
86 lines (68 loc) · 1.84 KB
/
sensitive_words.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
package sensitivewords
import (
"bufio"
"io"
"os"
)
type SensitiveWords struct {
trie *TrieTree
}
//New 返回敏感词库实例
func New() *SensitiveWords {
return &SensitiveWords{
trie: NewTrieTree(),
}
}
//Load 加载敏感词
func (sensitiveWords *SensitiveWords) Load(rd io.Reader) error {
buf := bufio.NewReader(rd)
for {
keywords, _, err := buf.ReadLine()
if err != nil {
if err == io.EOF {
break
}
return err
}
sensitiveWords.trie.Add(string(keywords))
}
return nil
}
//LoadFromFile 加载敏感词库文件
func (sensitiveWords *SensitiveWords) LoadFromFile(path string) error {
fs, err := os.Open(path)
defer fs.Close()
if err != nil {
return nil
}
return sensitiveWords.Load(fs)
}
//AddWord 添加敏感词
func (sensitiveWords *SensitiveWords) AddWord(word string) {
sensitiveWords.trie.Add(word)
}
//AddWords 添加敏感词数组
func (sensitiveWords *SensitiveWords) AddWords(words ...string) {
sensitiveWords.trie.AddWords(words...)
}
//Filter 过滤敏感词为*
func (sensitiveWords *SensitiveWords) Filter(input string) string {
return sensitiveWords.trie.Filter(input)
}
//Find 查找敏感词,找到第一个就退出
func (sensitiveWords *SensitiveWords) Find(input string) (sensitive bool, keyword string) {
return sensitiveWords.trie.Find(input)
}
//Check 是否包含敏感词
func (sensitiveWords *SensitiveWords) Check(input string) (sensitive bool) {
sensitive, _ = sensitiveWords.trie.Find(input)
return sensitive
}
//FindAll 查找ALL敏感词
func (sensitiveWords *SensitiveWords) FindAll(input string) (sensitive bool, results []string) {
return sensitiveWords.trie.FindAll(input)
}
//FindAny 找到N个敏感词才退出
func (sensitiveWords *SensitiveWords) FindAny(input string, count int) (sensitive bool, results []string) {
return sensitiveWords.trie.FindAny(input, count)
}