/
preload.go
143 lines (118 loc) · 2.32 KB
/
preload.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
package main
import (
"encoding/csv"
"io"
"log"
"os"
"strconv"
)
const (
WordwiseDictionaryPath = "resources/wordwise-dict-optimized.csv"
LemmaDictionaryPath = "resources/lemmatization-en.csv"
)
var wordwiseDict *map[string]DictRow
var lemmaDict *map[string]string
type DictRow struct {
Word string
Phoneme string
En string
Vi string
HintLvl int
}
func (ws *DictRow) meaning(isVietnamese bool) string {
if isVietnamese {
if len(ws.Phoneme) > 0 {
return ws.Phoneme + " " + ws.Vi
} else {
return ws.Vi
}
} else {
return ws.En
}
}
// Load Dict from CSV
func loadWordwiseDict() {
file, err := os.Open(WordwiseDictionaryPath)
if err != nil {
logFatalln("Error when open ", WordwiseDictionaryPath, "->", err)
}
defer func() {
err := file.Close()
if err != nil {
log.Println(err)
}
}()
reader := csv.NewReader(file)
dict := make(map[string]DictRow)
row := DictRow{}
// Read each record from csv
// skip header
record, err := reader.Read()
if err == io.EOF {
logFatalln("Empty csv file")
}
count := 0
for {
record, err = reader.Read()
if err == io.EOF {
break
}
if err != nil {
logFatalln("Error when scan word ", count, "->", err)
}
if len(record) < 5 {
log.Println("Invalid word: ", record)
continue
}
hintLv, err := strconv.Atoi(record[4])
if err != nil {
log.Println("Can't get hint_level: ", record, "->", err)
continue
}
row = DictRow{
Word: record[0],
Phoneme: record[1],
En: record[2],
Vi: record[3],
HintLvl: hintLv,
}
dict[row.Word] = row
count++
}
log.Println("--> Csv words:", count)
wordwiseDict = &dict
}
// Load Dict from CSV
func loadLemmatizerDict() {
file, err := os.Open(LemmaDictionaryPath)
if err != nil {
logFatalln("Error when open ", LemmaDictionaryPath, "->", err)
}
defer func() {
err := file.Close()
if err != nil {
log.Println(err)
}
}()
reader := csv.NewReader(file)
dict := make(map[string]string)
var record []string
count := 0
for {
record, err = reader.Read()
if err == io.EOF {
break
}
if err != nil {
logFatalln("Error when scan word ", count, "->", err)
}
if len(record) < 2 {
log.Println("Invalid word: ", record)
continue
}
dict[record[1]] = record[0]
count++
}
log.Println("--> Lemma pairs:", count)
lemmaDict = &dict
}