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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
#[macro_use]
extern crate error_chain;
extern crate kuchiki;
extern crate reqwest;
use kuchiki::traits::TendrilSink;
#[cfg(test)]
mod tests;
pub mod error;
pub use error::{Error, ErrorKind, Result};
#[derive(PartialEq, Debug)]
pub enum Lang {
Korean,
English,
Japanese,
Hanja,
Other(String),
}
pub struct Word {
pub word: String,
pub meaning: String,
pub pronounce: String,
pub lang: Lang,
}
impl std::fmt::Display for Word {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
if let Lang::Other(ref d) = self.lang {
write!(f, "({}) ", d)?;
}
write!(f, "{} ", self.word)?;
if !self.pronounce.is_empty() {
write!(f, "{} ", self.pronounce)?;
}
write!(f, "{}", self.meaning)
}
}
pub fn search(word: &str) -> Result<Word> {
ensure!(!word.is_empty(), ErrorKind::EmptyWord);
let mut addr = String::from("http://dic.daum.net/search.do?q=");
addr.push_str(word);
let mut resp = reqwest::get(&addr)?;
let document = kuchiki::parse_html().one(resp.text()?);
let rel = document
.select(".link_speller")
.unwrap()
.map(|r| r.text_contents())
.collect::<Vec<String>>();
ensure!(rel.is_empty(), ErrorKind::RelativeResultFound(rel));
let sbox = document
.select_first(".search_box")
.map_err(|_| ErrorKind::WordNotFound)?;
let sbox = sbox.as_node();
let word = sbox.select_first(".txt_cleansch")
.or_else(|_| sbox.select_first(".txt_searchword"))
.or_else(|_| sbox.select_first(".txt_hanjaword"))
.map_err(|_| ErrorKind::ParsingFailed)?
.text_contents();
let lang: Lang = {
let lang = sbox.ancestors()
.next()
.and_then(|a| a.select_first(".tit_word").ok())
.ok_or(ErrorKind::ParsingFailed)?
.text_contents();
if lang.starts_with("한국") {
Lang::Korean
} else if lang.starts_with("영") {
Lang::English
} else if lang.starts_with("일") {
Lang::Japanese
} else if lang.starts_with("한자") {
Lang::Hanja
} else {
Lang::Other(lang)
}
};
let meaning = sbox.select(".txt_search")
.map_err(|_| ErrorKind::ParsingFailed)?
.map(|m| m.text_contents())
.collect::<Vec<String>>()
.join(", ");
let pronounce = match lang {
Lang::Hanja => sbox.select_first(".sub_read"),
_ => sbox.select_first(".txt_pronounce"),
}.map(|p| p.text_contents())
.unwrap_or_default();
Ok(Word {
word,
meaning,
pronounce,
lang,
})
}