github.com/insionng/yougam@v0.0.0-20170714101924-2bc18d833463/libraries/trie/trie.go (about) 1 package main 2 3 import ( 4 "fmt" 5 "strings" 6 ) 7 8 type trieTree struct { 9 key rune 10 word []rune 11 isword bool 12 childNodes map[rune]*trieTree 13 } 14 15 func (t *trieTree) Insert(word []rune, index int) { 16 //fmt.Println("插入的关键词是", string(word)) 17 //获取第index个字 18 key := word[index] 19 //fmt.Println("保存的key是:", string(key)) 20 index++ 21 //如果以前保存这个字,则找下一个节点 22 if _, found := t.childNodes[key]; found { 23 t.childNodes[key].Insert(word, index) 24 } else { 25 //如果没有保存过,则保存这个key 26 trie := new(trieTree) 27 t.childNodes[key] = trie 28 trie.key = key 29 //判断是否到词的最后 30 if index == len(word) { 31 trie.word = word 32 trie.isword = true 33 } else { 34 trie.childNodes = make(map[rune]*trieTree) 35 trie.Insert(word, index) 36 } 37 } 38 39 } 40 41 func (t *trieTree) Replace(msg []rune) string { 42 //保存根节点指针 43 var root *trieTree = t 44 for index, s := range msg { 45 if _, found := t.childNodes[s]; found { 46 if t.childNodes[s].isword { 47 wordlen := len(t.childNodes[s].word) 48 copy(msg[index-wordlen+1:index+1], []rune(strings.Repeat("*", wordlen))) 49 fmt.Println("找到过滤词", string(t.childNodes[s].word), "===>", string(msg[index-wordlen+1:index+1])) 50 continue 51 } 52 t = t.childNodes[s] 53 } else { 54 t = root 55 56 } 57 } 58 return string(msg) 59 } 60 61 func main() { 62 //初始化根节点 63 trie := new(trieTree) 64 trie.childNodes = make(map[rune]*trieTree) 65 66 var wordList = []string{"我擦", "我草", "我操", "fuck", "傻逼", "SB"} 67 68 var msg string = "昨天见到你妈,逼我买房子,你说我怎么办呢,fuck了,我擦" 69 70 for _, word := range wordList { 71 //子节点开始保存数据 72 word = strings.ToLower(word) 73 trie.Insert([]rune(word), 0) 74 } 75 76 msg = trie.Replace([]rune(msg)) 77 fmt.Println(msg) 78 //fmt.Printf("%s\n%v\n", trie.childNodes, trie.childNodes) 79 //printMap(trie) 80 } 81 82 func printMap(trie *trieTree) { 83 for _, v := range trie.childNodes { 84 fmt.Println("key:", string(v.key), "word:", string(v.word), "isword:", v.isword) 85 printMap(v) 86 } 87 88 }