-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdict.go
73 lines (62 loc) · 1.21 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
package a5er
import (
"encoding/csv"
"fmt"
"io"
"os"
"sort"
"unicode/utf8"
)
type Dictionary []*dict
func (d Dictionary) String() string {
var o string
for _, dd := range d {
o += fmt.Sprintf("[%s, %s]", dd.Key, dd.Value)
}
return o
}
type dict struct {
Key, Value string
}
func (d *Dictionary) LoadCSV(filepath string) error {
f, err := os.Open(filepath)
if err != nil {
return err
}
defer f.Close()
csvReader := csv.NewReader(f)
for {
rec, err := csvReader.Read()
if err == io.EOF {
break
}
if err != nil {
return err
}
key, value := rec[0], rec[1]
*d = append(*d, &dict{key, value})
}
// より長くマッチした単語を優先して置換対象とするため、
// 日本語文字列の降順でソート
d.sort()
return nil
}
func (d *Dictionary) LoadMap(words map[string]string) {
for key, value := range words {
*d = append(*d, &dict{key, value})
}
d.sort()
}
func (d *Dictionary) sort() {
sort.SliceStable(*d, func(i, j int) bool {
return utf8.RuneCountInString((*d)[i].Key) > utf8.RuneCountInString((*d)[j].Key)
})
}
func (d *Dictionary) containsValue(value string) bool {
for _, dd := range *d {
if value == dd.Value {
return true
}
}
return false
}