-
Notifications
You must be signed in to change notification settings - Fork 0
/
merriam-webster.go
105 lines (98 loc) · 2.51 KB
/
merriam-webster.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
package mydictionary
import (
"net/url"
"strings"
"time"
"github.com/PuerkitoBio/goquery"
)
const merriamWebsterName = "Merriam Webster"
// MerriamWebsterStruct : Merriam Webster struct
type MerriamWebsterStruct struct {
cache CacheStruct
}
// GetServiceName : get service name
func (service *MerriamWebsterStruct) GetServiceName() (value string) {
value = merriamWebsterName
return
}
// GetCache : get cache
func (service *MerriamWebsterStruct) GetCache() (cache *CacheStruct) {
cache = &service.cache
return
}
// Query : query vocabulary
func (service *MerriamWebsterStruct) Query(vocabularyAsk VocabularyAskStruct) (vocabularyAnswer VocabularyAnswerStruct) {
var (
err error
queryString string
item CacheItemStruct
document *goquery.Document
selection1 *goquery.Selection
selection2 *goquery.Selection
selection3 *goquery.Selection
selection4 *goquery.Selection
)
// set
vocabularyAnswer.SourceName = merriamWebsterName
vocabularyAnswer.Location.TableType = Online
vocabularyAnswer.Location.TableIndex = -1
vocabularyAnswer.Location.ItemIndex = -1
// query cache
queryString = url.QueryEscape(vocabularyAsk.Word)
item, err = service.cache.Query(queryString)
if err == nil {
goto SET
}
// query online
// no phrase is contained by Merriam Webster
if strings.Contains(queryString, "%20") {
item.Status = "null: MW01"
goto ADD
}
// get page
document, err = goquery.NewDocument("https://www.merriam-webster.com/dictionary/" + queryString)
if err != nil {
item.Status = err.Error()
goto ADD
}
// locate
selection1 = document.Find(".learners-def")
if selection1.Nodes == nil {
item.Status = "null: MW02"
goto ADD
}
selection2 = selection1.Eq(0);
// get word
selection3 = selection2.Prev().Find("em")
if selection3.Nodes == nil {
item.Status = "null: MW03"
goto ADD
}
item.Word = selection3.Text()
// get define
selection4 = selection2.Find(".dtText");
if selection4.Nodes == nil {
item.Status = "null: MW04"
goto ADD
}
for i := 0; i < selection4.Size(); i++ {
item.Definition = append(item.Definition, selection4.Eq(i).Text());
}
// mark difference
if strings.Compare(queryString, url.QueryEscape(item.Word)) != 0 {
item.Status = "different"
} else {
item.Status = Basic
}
ADD:
// add to cache
item.QueryString = queryString
item.CreationTime = time.Now().Unix()
service.cache.Add(item)
SET:
// set
vocabularyAnswer.Word = item.Word
vocabularyAnswer.Definition = item.Definition
vocabularyAnswer.Status = item.Status
return
}