forked from liuzl/gocc
-
Notifications
You must be signed in to change notification settings - Fork 23
/
opencc.go
222 lines (207 loc) · 4.94 KB
/
opencc.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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
// Package opencc is a golang port of OpenCC(Open Chinese Convert 開放中文轉換)
package opencc
import (
"embed"
"encoding/json"
"flag"
"fmt"
"os"
"path"
"reflect"
"runtime"
"strings"
"github.com/liuzl/da"
)
//go:embed config
var cf embed.FS
//go:embed dictionary
var df embed.FS
var (
// Dir is the parent dir for config and dictionary
Dir = flag.String("dir", defaultDir(), "dict dir")
)
func defaultDir() string {
if runtime.GOOS == "windows" {
return `C:\gocc\`
}
if goPath, ok := os.LookupEnv("GOPATH"); ok {
return goPath + "/src/github.com/longbridge/opencc/"
} else {
return `/usr/local/share/gocc/`
}
}
// Group holds a sequence of dicts
type Group struct {
Files []string
Dicts []*da.Dict
}
func (g *Group) String() string {
return fmt.Sprintf("%+v", g.Files)
}
// OpenCC contains the converter
type OpenCC struct {
Conversion string
Description string
DictChains []*Group
}
var conversions = map[string]struct{}{
"hk2s": {}, "s2hk": {}, "s2t": {}, "s2tw": {}, "s2twp": {},
"t2hk": {}, "t2s": {}, "t2tw": {}, "tw2s": {}, "tw2sp": {},
"s2hk-finance": {},
}
// New construct an instance of OpenCC.
//
// Supported conversions: s2t, t2s, s2tw, tw2s, s2hk, hk2s, s2twp, tw2sp, t2tw, t2hk, s2hk-finance
func New(conversion string) (*OpenCC, error) {
if _, has := conversions[conversion]; !has {
return nil, fmt.Errorf("%s not valid", conversion)
}
cc := &OpenCC{Conversion: conversion}
err := cc.initDict()
if err != nil {
return nil, err
}
return cc, nil
}
// Convert string from Simplified Chinese to Traditional Chinese or vice versa
func (cc *OpenCC) Convert(in string) (string, error) {
var token string
preOffset := 10
for _, group := range cc.DictChains {
r := []rune(in)
var tokens []string
for i := 0; i < len(r); {
offset := len(r)
if offset > i+preOffset {
offset = i + preOffset
}
s := r[i:offset]
max := 0
for _, dict := range group.Dicts {
ret, err := dict.PrefixMatch(string(s))
if err != nil {
return "", err
}
if len(ret) > 0 {
o := ""
for k, v := range ret {
if len(k) > max {
max = len(k)
token = v[0]
o = k
}
}
i += len([]rune(o))
break
}
}
if max == 0 { //no match
token = string(r[i])
i++
}
tokens = append(tokens, token)
}
in = strings.Join(tokens, "")
}
return in, nil
}
func (cc *OpenCC) initDict() error {
if cc.Conversion == "" {
return fmt.Errorf("conversion is not set")
}
configFile := path.Join("config", cc.Conversion+".json")
body, err := cf.ReadFile(configFile)
if err != nil {
return err
}
var m interface{}
err = json.Unmarshal(body, &m)
if err != nil {
return err
}
config := m.(map[string]interface{})
name, has := config["name"]
if !has {
return fmt.Errorf("name not found in %s", configFile)
}
cc.Description = name.(string)
chain, has := config["conversion_chain"]
if !has {
return fmt.Errorf("conversion_chain not found in %s", configFile)
}
if dictChain, ok := chain.([]interface{}); ok {
for _, v := range dictChain {
if d, ok := v.(map[string]interface{}); ok {
if gdict, has := d["dict"]; has {
if dict, is := gdict.(map[string]interface{}); is {
group, err := cc.addDictChain(dict)
if err != nil {
return err
}
cc.DictChains = append(cc.DictChains, group)
}
} else {
return fmt.Errorf("should have dict inside conversion_chain")
}
} else {
return fmt.Errorf("should be map inside conversion_chain")
}
}
} else {
return fmt.Errorf("format %+v not correct in %s",
reflect.TypeOf(dictChain), configFile)
}
return nil
}
func (cc *OpenCC) addDictChain(d map[string]interface{}) (*Group, error) {
t, has := d["type"]
if !has {
return nil, fmt.Errorf("type not found in %+v", d)
}
if typ, ok := t.(string); ok {
ret := &Group{}
switch typ {
case "group":
ds, has := d["dicts"]
if !has {
return nil, fmt.Errorf("no dicts field found")
}
dicts, is := ds.([]interface{})
if !is {
return nil, fmt.Errorf("dicts field invalid")
}
for _, dict := range dicts {
if d, is := dict.(map[string]interface{}); is {
group, err := cc.addDictChain(d)
if err != nil {
return nil, err
}
ret.Files = append(ret.Files, group.Files...)
ret.Dicts = append(ret.Dicts, group.Dicts...)
} else {
return nil, fmt.Errorf("dicts items invalid")
}
}
case "ocd2", "txt":
file, has := d["file"]
if !has {
return nil, fmt.Errorf("no file field found")
}
filename := strings.Replace(path.Join("dictionary", file.(string)), ".ocd2", ".txt", 1)
f, err := df.Open(filename)
if err != nil {
return nil, err
}
daDict, err := da.Build(f)
if err != nil {
return nil, err
}
ret.Files = append(ret.Files, file.(string))
ret.Dicts = append(ret.Dicts, daDict)
default:
return nil, fmt.Errorf("type should be txt or group")
}
return ret, nil
}
return nil, fmt.Errorf("type should be string")
}