-
Notifications
You must be signed in to change notification settings - Fork 7
/
dict.go
87 lines (70 loc) · 1.34 KB
/
dict.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
package gotokenizer
import (
"bufio"
"errors"
"io"
"os"
"strings"
)
// DefaultMinTokenLen is default minimum tokenLen
var DefaultMinTokenLen = 2
// DictRecord records dict meta info
type DictRecord struct {
TF string
Token string
POS string //part of speech
}
// Dict records Records and DictPath etc.
type Dict struct {
Records map[string]DictRecord
minTokenLen int
DictPath string
maxLen int
isLoaded bool
}
// NewDict returns a newly initialized Dict object
func NewDict(dictPath string) *Dict {
return &Dict{
Records: make(map[string]DictRecord),
DictPath: dictPath,
minTokenLen: DefaultMinTokenLen,
isLoaded: false,
}
}
// Load that loads Dict
func (dict *Dict) Load() error {
if dict.isLoaded {
return errors.New("dict isLoaded")
}
fi, err := os.Open(dict.DictPath)
if err != nil {
return err
}
defer fi.Close()
br := bufio.NewReader(fi)
for {
a, _, c := br.ReadLine()
if c == io.EOF {
break
}
res := strings.Split(string(a), " ")
var TF, pos string
token := res[0]
if len(res) > 1 {
TF = res[1]
pos = res[2]
}
currLen := len([]rune(token))
if currLen > dict.maxLen {
dict.maxLen = currLen
}
if len([]rune(token)) >= dict.minTokenLen {
dict.Records[token] = DictRecord{
TF: TF,
POS: pos,
}
}
}
dict.isLoaded = true
return nil
}