dict/dict.go

87 lines
1.6 KiB
Go
Raw Normal View History

2015-07-28 10:09:26 +02:00
package main
import (
"bufio"
"fmt"
"net/http"
"os"
2015-07-28 10:34:56 +02:00
"regexp"
2015-07-28 10:09:26 +02:00
"strings"
)
const (
BASE = "dict.cc/?s="
VAR1 = "var c1Arr = new Array("
VAR2 = "var c2Arr = new Array("
SUFF = ");"
)
func main() {
if len(os.Args) < 2 {
println("usage:", os.Args[0], "word [{de|es|fr|en...}{de|es|fr|en|...}]")
return
}
fromto := ""
if len(os.Args) > 2 {
fromto = os.Args[2] + "."
}
r, err := http.Get("http://" + fromto + BASE + os.Args[1])
if err != nil {
println("error:", err.Error())
return
}
defer r.Body.Close()
byline := bufio.NewScanner(r.Body)
var left, right []string
for byline.Scan() {
line := byline.Text()
if strings.HasPrefix(line, VAR1) {
line = strings.TrimPrefix(line, VAR1)
line = strings.TrimSuffix(line, SUFF)
2015-07-28 10:25:44 +02:00
left = strings.Split(line, `","`)
2015-07-28 10:09:26 +02:00
} else if strings.HasPrefix(line, VAR2) {
line = strings.TrimPrefix(line, VAR2)
line = strings.TrimSuffix(line, SUFF)
2015-07-28 10:25:44 +02:00
right = strings.Split(line, `","`)
2015-07-28 10:09:26 +02:00
break
}
}
if len(left) != len(right) {
println("error: arrays of different length")
2015-07-28 10:25:44 +02:00
fmt.Println(strings.Join(left, "\n"), len(left))
fmt.Println(strings.Join(right, "\n"), len(right))
2015-07-28 10:09:26 +02:00
return
}
2015-07-28 10:18:22 +02:00
ml := 5
for _, v := range right {
if len(v) > ml {
ml = len(v)
}
}
if ml > 40 {
ml = 40
}
2015-07-28 10:34:56 +02:00
re := regexp.MustCompile(`\('"„)`)
2015-07-28 10:18:22 +02:00
for i, _ := range right {
2015-07-28 10:25:44 +02:00
a := strings.Trim(right[i], `„"`)
b := strings.Trim(left[i], `„"`)
2015-07-28 10:34:56 +02:00
a = re.ReplaceAllString(a, `$1`)
b = re.ReplaceAllString(b, `$1`)
2015-07-28 10:09:26 +02:00
if a == "" {
continue
}
2015-07-28 10:18:22 +02:00
// TODO: wrap when len(a) > ml
fmt.Printf("%*s → %s\n", ml, a, b)
2015-07-28 10:09:26 +02:00
}
}