-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcedict.go
118 lines (105 loc) · 2.48 KB
/
cedict.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
package main
import (
"fmt"
"os"
"strings"
"github.com/alisonatwork/cedict/db"
"github.com/alisonatwork/cedict/lookup"
"github.com/alisonatwork/cedict/pinyin"
)
type matchStrategy int
const (
exact matchStrategy = iota
splitChar
splitGreedy
)
func printEntries(entries []*lookup.Entry) {
for _, e := range entries {
defs := strings.Join(e.Definitions, "/")
if len(e.Pinyin) > 0 {
fmt.Printf("%s\t[%s]\t/%s/\n", e.Simplified, pinyin.NumberToMark(e.Pinyin), pinyin.NumberToMark(defs))
} else {
fmt.Printf("%s\n", e.Simplified)
}
}
}
func output(strategy matchStrategy, lookup lookup.Lookup, word string) {
// we use simplified as the authoritative index lookup because it returns more hits
// the problem: if we search 面 we want both noodles and face, not just face (simplified wins)
// if we search 碗 we just want bowl, not 4 different variants of bowl (traditional wins)
entries := lookup.Simplified[word]
if len(entries) == 0 {
entries = lookup.Traditional[word]
}
if len(entries) == 0 {
if len(word) > 1 {
switch strategy {
case exact:
break
case splitChar:
for _, c := range strings.Split(word, "") {
output(strategy, lookup, c)
}
return
case splitGreedy:
printEntries(lookup.Match(word))
return
}
}
// convert traditional to simplified before printing unknown char
for _, c := range strings.Split(word, "") {
entries = lookup.Traditional[c]
if len(entries) == 0 {
fmt.Printf("%s", c)
} else {
fmt.Printf("%s", entries[0].Simplified)
}
}
fmt.Printf("\n")
} else {
printEntries(entries)
}
}
func main() {
if len(os.Args) == 1 {
return
}
if len(os.Args) == 2 && os.Args[1] == "get" {
err := db.Download()
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %s!\n", err)
}
return
}
var strategy = exact
var words []string
if len(os.Args) > 2 && os.Args[1] == "-m" {
words = os.Args[2:]
// need a way to select strategies
// strategy = splitChar
strategy = splitGreedy
} else {
words = os.Args[1:]
}
db, err := db.Open()
if os.IsNotExist(err) {
fmt.Fprintf(os.Stderr, "Dictionary not found: get first!\n")
return
} else if err != nil {
fmt.Fprintf(os.Stderr, "Error: %s!\n", err)
return
}
lookup, err := lookup.Build(db)
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %s!\n", err)
return
}
err = db.Close()
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %s!\n", err)
return
}
for _, word := range words {
output(strategy, lookup, word)
}
}