110 lines
2.0 KiB
Go
110 lines
2.0 KiB
Go
package main
|
|
|
|
import (
|
|
"bufio"
|
|
"fmt"
|
|
"net/http"
|
|
"os"
|
|
"regexp"
|
|
"strings"
|
|
)
|
|
|
|
const (
|
|
BASE = "dict.cc/?s="
|
|
VAR1 = "var c1Arr = new Array("
|
|
VAR2 = "var c2Arr = new Array("
|
|
SUFF = ");"
|
|
)
|
|
|
|
// is going to be set in winsize.go, if run on unix
|
|
var Width = 80
|
|
|
|
func main() {
|
|
if len(os.Args) < 2 || os.Args[1][0] == '-' {
|
|
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)
|
|
left = strings.Split(line, `","`)
|
|
} else if strings.HasPrefix(line, VAR2) {
|
|
line = strings.TrimPrefix(line, VAR2)
|
|
line = strings.TrimSuffix(line, SUFF)
|
|
right = strings.Split(line, `","`)
|
|
break
|
|
}
|
|
}
|
|
|
|
if len(left) != len(right) {
|
|
println("error: arrays of different length")
|
|
fmt.Println(strings.Join(left, "\n"), len(left))
|
|
fmt.Println(strings.Join(right, "\n"), len(right))
|
|
return
|
|
}
|
|
|
|
ml := 25
|
|
|
|
for _, v := range right {
|
|
if len(v) > ml {
|
|
ml = len(v)
|
|
}
|
|
}
|
|
|
|
if ml > (Width / 2) {
|
|
ml = Width / 2
|
|
}
|
|
|
|
re := regexp.MustCompile(`\\(['"„])`)
|
|
for i, _ := range right {
|
|
a := strings.Trim(right[i], `„"`)
|
|
b := strings.Trim(left[i], `„"`)
|
|
a = re.ReplaceAllString(a, `$1`)
|
|
b = re.ReplaceAllString(b, `$1`)
|
|
|
|
if a == "" {
|
|
continue
|
|
}
|
|
|
|
for len(a) > ml {
|
|
if i := strings.LastIndex(a[:ml], " "); i > 0 {
|
|
fmt.Printf("%*s\n", ml, a[:i])
|
|
a = a[i:]
|
|
} else {
|
|
break
|
|
}
|
|
}
|
|
|
|
fmt.Printf("%*s → ", ml, a)
|
|
for len(b) > ml {
|
|
if i := strings.LastIndex(b[:ml], " "); i > 0 {
|
|
fmt.Println(b[:i])
|
|
fmt.Printf("%*s ", ml, "")
|
|
b = b[i:]
|
|
} else {
|
|
break
|
|
}
|
|
}
|
|
fmt.Println(b)
|
|
}
|
|
}
|