-
Notifications
You must be signed in to change notification settings - Fork 1
/
rules.go
80 lines (62 loc) · 1.56 KB
/
rules.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
package vocx
import (
"encoding/json"
"fmt"
"regexp"
"strings"
)
// Override is used to replace a full word.
type Override struct {
Esperanto string `json:"eo"`
Polish string `json:"pl"`
}
// Fragment is used to replace a fragment of a word.
type Fragment struct {
Match string `json:"match"`
Replace string `json:"replace"`
}
// Rules capture the set of rules for a transcription.
type Rules struct {
Letters map[string]string `json:"letters"`
Fragments []Fragment `json:"fragments"`
Overrides []Override `json:"overrides"`
Numbers map[string]string `json:"numbers"`
}
func (r *Rules) findOverride(word string) string {
punctuation := `,.!?;:*"'«»„“<>()[]{}`
prefix := string(word[0])
prefixed := strings.Contains(punctuation, prefix)
if prefixed {
word = word[1:]
}
postfix := string(word[len(word)-1])
postfixed := strings.Contains(punctuation, postfix)
if postfixed {
word = word[0 : len(word)-1]
}
word = strings.ToLower(word)
for _, override := range r.Overrides {
if strings.ToLower(override.Esperanto) == word {
return fmt.Sprintf("%s%s%s", iff(prefixed, prefix), override.Polish, iff(postfixed, postfix))
}
}
return ""
}
func loadRules(data string) (*Rules, error) {
r := &Rules{}
if err := json.NewDecoder(strings.NewReader(data)).Decode(&r); err != nil {
return nil, err
}
for _, fragment := range r.Fragments {
if _, err := regexp.Compile(fragment.Match); err != nil {
return nil, err
}
}
return r, nil
}
func iff(expr bool, value string) string {
if expr {
return value
}
return ""
}