-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
111 lines (98 loc) · 2.42 KB
/
main.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
package gohanspell
import (
"encoding/json"
"errors"
"io/ioutil"
"math/rand"
"net/http"
"net/url"
"strings"
"time"
)
const MaxLen = 280
const PusanUnivURL = "http://speller.cs.pusan.ac.kr/results"
type Correction struct {
Str string `json:"str"`
ErrInfo []struct {
Help string `json:"help"`
ErrorIdx int `json:"errorIdx"`
CorrectMethod int `json:"correctMethod"`
Start int `json:"start"`
End int `json:"end"`
OrgStr string `json:"orgStr"`
CandWord string `json:"candWord"`
} `json:"errInfo"`
Idx int `json:"idx"`
}
func countByWord(s string) int {
return len(strings.Split(s, " "))
}
func splitByWord(s string) []string {
ret := make([]string, 0)
sentences := strings.Split(s, "\n")
s = ""
for len(sentences) > 0 {
if countByWord(s) + countByWord(sentences[0]) > MaxLen {
s = strings.TrimSpace(s)
ret = append(ret, s)
s = sentences[0]
} else {
s += "\t" + sentences[0]
}
if len(sentences) == 1 {
sentences = nil
break
}
sentences = sentences[1:]
}
if len(s) > 0 {
ret = append(ret, s)
}
return ret
}
func mergeCorrection(c Correction) string {
rand.Seed(time.Now().Unix())
s := c.Str
for _, e := range c.ErrInfo {
candWord := e.CandWord
if strings.Count(candWord, "|") > 0 {
words := strings.Split(candWord, "|")
candWord = words[rand.Intn(len(words))]
}
s = strings.ReplaceAll(s, e.OrgStr, candWord)
}
return s
}
// PostPusanUniv is correcting spelling and smth lol yeah~
// error would be three of these
// - error while sending POST data
// - response from Pusan Uni is not 200(status OK)
// - invalid input which causes no response from Pusan Uni
func PostPusanUniv(s string) (string, error) {
txt := ""
for _, sentence := range splitByWord(s) {
body := url.Values{}
body.Set("text1", sentence)
resp, err := http.PostForm(PusanUnivURL, body)
if err != nil {
return "", err
}
if resp.StatusCode != http.StatusOK {
return "", errors.New("network error")
}
data, err := ioutil.ReadAll(resp.Body)
if err == nil {
raw := strings.Split(strings.Split(string(data), "data = [{")[1], "}];")[0]
raw = "{" + raw + "}"
correction := Correction{}
err = json.Unmarshal([]byte(raw), &correction)
if err != nil {
return "", err
}
txt += "\n" + strings.ReplaceAll(mergeCorrection(correction), "\t", "\n")
}
resp.Body.Close()
}
txt = strings.TrimSpace(txt)
return txt, nil
}