-
Notifications
You must be signed in to change notification settings - Fork 0
/
tokenizer.go
62 lines (53 loc) · 1.33 KB
/
tokenizer.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
package main
import (
"regexp"
"strings"
englishStemmer "github.com/kljensen/snowball/english"
)
type tokenizer struct {
stopWords map[string]struct{}
punctuationRegex *regexp.Regexp
}
func newTokenizer() *tokenizer {
stopWords := []string{
"the", "be", "to", "of", "and", "a", "in", "that", "have",
"I", "it", "for", "not", "on", "with", "he", "as", "you",
"do", "at", "this", "but", "his", "by", "from", "wikipedia",
}
stopWordsSet := make(map[string]struct{})
for _, word := range stopWords {
stopWordsSet[word] = struct{}{}
}
re := regexp.MustCompile(`[^\w]`)
return &tokenizer{
stopWords: stopWordsSet,
punctuationRegex: re,
}
}
func (t *tokenizer) tokenizeSingelWord(word string) string {
// lowercase each token
word = strings.ToLower(word)
// remove any punctuation
word = t.punctuationRegex.ReplaceAllString(word, "")
if word == "" {
return ""
}
// filter out if stopword
if _, ok := t.stopWords[word]; ok {
return ""
}
// apply stemming
stemmed := englishStemmer.Stem(word, true)
return stemmed
}
func (t *tokenizer) tokenize(text string) []string {
var tokens []string
// split text on white space and then tokenize
for _, word := range strings.Fields(text) {
tokenized := t.tokenizeSingelWord(word)
if tokenized != "" {
tokens = append(tokens, tokenized)
}
}
return tokens
}