刚学Go语言练手,用于敏感词匹配
字典树的Go语言实现
1 | package triecheck |
测试程序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
69package main
import (
. "./trie_check"
"bufio"
"fmt"
"io"
"io/ioutil"
"os"
"time"
)
var tc = new(TrieTree)
func processLine(line []byte) {
tc.AddWord(string(line))
}
func ReadLine(filePth string, hookfn func([]byte)) error {
f, err := os.Open(filePth)
if err != nil {
return err
}
defer f.Close()
bfRd := bufio.NewReader(f)
for {
line, _, err := bfRd.ReadLine()
hookfn(line)
if err != nil {
if err == io.EOF {
return nil
}
return err
}
}
return nil
}
func main() {
var start_time = time.Now().UnixNano()
//敏感词存在out6.txt中,每行一个词
ReadLine("out6.txt", processLine)
var end_time = time.Now().UnixNano()
fmt.Println("Create trie tree:", float64(end_time-start_time)/1000000, "ms")
//需要过滤敏感词的文件在out_test.txt中
fi, err := os.Open("out_test.txt")
if err != nil {
panic(err)
}
defer fi.Close()
fd, err := ioutil.ReadAll(fi)
start_time = time.Now().UnixNano()
for i := 1; i < 100; i++ {
tc.MinReplaceWith(string(fd), "*")
}
out, changed := tc.MinReplaceWith("fuckfUCKfucao 操蛋 啊啊会CKFu##Ck昂送伞", "*")
end_time = time.Now().UnixNano()
fmt.Println(out, changed)
fmt.Println(float64(end_time-start_time)/1000000, "ms")
start_time = time.Now().UnixNano()
for i := 1; i < 100; i++ {
tc.MaxReplaceWith(string(fd), "*")
}
out3, changed := tc.MaxReplaceWith("fuckfUCKfucao 操蛋 啊啊会CKFu##Ck 昂送伞", "*")
end_time = time.Now().UnixNano()
fmt.Println(out3, changed)
fmt.Println(float64(end_time-start_time)/1000000, "ms")
}