-
Notifications
You must be signed in to change notification settings - Fork 0
/
token.go
92 lines (76 loc) · 1.47 KB
/
token.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
87
88
89
90
91
92
package txt
import (
"errors"
"strings"
"github.com/sahilm/fuzzy"
)
type Token struct {
Value string `json:"value"`
Label string `json:"label"`
fuzzy.Match
}
type Tokens []*Token
func NewToken(label, val string) *Token {
return &Token{
Value: val,
Label: label,
}
}
func Tokenize(ana *Analyzer, text string) (Tokens, error) {
var (
toks Tokens
tokens []string
)
if ana.sep == nil {
tokens = []string{text}
} else {
tokens = strings.FieldsFunc(text, ana.sep)
}
if len(tokens) == 0 {
return toks, errors.New("strings.FieldsFunc returned an empty slice or the string was empty")
}
for _, label := range tokens {
tok := label
for _, norm := range ana.normalizers {
tok = norm(tok)
}
if ana.RmStopWords() {
if ana.IsStopWord(strings.ToLower(tok)) {
continue
}
}
if tok != "" {
toks = append(toks, NewToken(label, tok))
}
}
return toks, nil
}
func (toks Tokens) Find(q string) Tokens {
var tokens Tokens
for i, tok := range toks {
if tok.Value == q {
tok.Match = fuzzy.Match{
Index: i,
Str: tok.Label,
}
tokens = append(tokens, tok)
}
}
return tokens
}
func (toks Tokens) FuzzyFind(q string) Tokens {
var tokens Tokens
for _, m := range fuzzy.FindFrom(q, toks) {
tok := toks[m.Index]
tok.Match = m
tok.Match.Str = tok.Label
tokens = append(tokens, tok)
}
return tokens
}
func (toks Tokens) String(i int) string {
return toks[i].Value
}
func (toks Tokens) Len() int {
return len(toks)
}