/
dict.go
59 lines (52 loc) · 1.3 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
package main
import (
"xml"
"http"
"strings"
"fmt"
)
const template = "http://%s.wikipedia.org/w/api.php?action=query&titles=%s&prop=langlinks&redirects&format=xml"
type Dict struct {
original string
langs []string
trans map[string]string
}
func emptyDict() *Dict {
return &Dict{"", make([]string, 0), make(map[string]string)}
}
func (d *Dict) String() string {
ret := []string{"Original: " + d.original}
for i := 0; i != len(d.langs); i++ {
ret = append(ret, fmt.Sprintf("%s: %s", d.langs[i], d.trans[d.langs[i]]))
}
return strings.Join(ret, "\n")
}
func (d *Dict) add(translations []Ll) {
langs := make([]string, len(translations))
for i, t := range translations {
langs[i] = t.Lang
d.trans[t.Lang] = t.Translation
}
d.langs = append(d.langs, langs...)
}
func NewDict(lang, title string) *Dict {
d := emptyDict()
parsed := new(Api)
base := fmt.Sprintf(template, lang, http.URLEscape(title))
response, _, _ := http.Get(base)
defer response.Body.Close()
xml.Unmarshal(response.Body, parsed)
d.original = parsed.Title
for {
d.add(parsed.Ll)
cont := parsed.Any.Langlinks.Llcontinue
if cont == "" {
break
}
parsed = new(Api)
newResponse, _, _ := http.Get(base + "&llcontinue=" + cont)
defer newResponse.Body.Close()
xml.Unmarshal(newResponse.Body, parsed)
}
return d
}