-
Notifications
You must be signed in to change notification settings - Fork 0
/
text.go
58 lines (47 loc) · 1.18 KB
/
text.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
package purify
import (
"log"
"regexp"
"strings"
)
// This variable matches basic patterns to the possibly intended runes
var replacer *strings.Replacer
func init() {
replacer = strings.NewReplacer(
"@", "a", "(", "c", "3", "e",
"1", "i", "!", "i", "0", "o",
"9", "q", "5", "s", "v", "u",
"2", "z", "+", "t",
)
}
// Filter sanitizes a given text based on a passed trie of bad words
func Filter(trie *Trie, words string) string {
r, err := regexp.Compile("[^a-zA-Z]+")
if err != nil {
log.Fatal(err)
}
wordsSlice := strings.Split(words, " ")
wordsDone := make([]string, 0)
for _, word := range wordsSlice {
filtered := word
word = strings.ToLower(word)
replaced := replacer.Replace(word)
rWord := r.ReplaceAllString(word, "")
rReplaced := r.ReplaceAllString(replaced, "")
if trie.Find(word) || trie.Find(replaced) || trie.Find(rWord) || trie.Find(rReplaced) {
filtered = clean(word)
}
wordsDone = append(wordsDone, filtered)
}
return strings.Join(wordsDone, " ")
}
func clean(s string) string {
var sb strings.Builder
sb.WriteByte(s[0])
size := len(s)
for i := 2; i < size; i++ {
sb.WriteRune('*')
}
sb.WriteByte(s[size-1])
return sb.String()
}