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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
#[cfg(test)]
mod test_dict;
use std::borrow::Borrow;
use std::collections::HashMap;
use std::fs::File;
use std::hash::Hash;
use std::io;
use std::iter::FromIterator;
use std::path::Path;
extern crate stringedits;
use self::stringedits::Edit;
pub const ASCII_LOWERCASE: &str = "abcdefghijklmnopqrstuvwxyz";
pub type Result<T> = std::result::Result<T, IOError>;
#[derive(Debug)]
pub enum IOError {
IO(io::Error),
ParseInt(usize, std::num::ParseIntError),
BadFormat(usize),
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Dict {
map: HashMap<String, usize>,
alphabet: Box<[char]>,
}
fn charslice(s: impl AsRef<str>) -> Box<[char]> {
s.as_ref().chars().collect::<Vec<char>>().into_boxed_slice()
}
impl Default for Dict {
fn default() -> Self {
Dict::new_ascii_lowercase()
}
}
impl Dict {
pub fn get<Q>(&self, word: &Q) -> Option<&usize>
where
String: Borrow<Q>,
Q: Eq + Hash + ?Sized,
{
self.map.get(word)
}
pub fn new(alphabet: impl AsRef<str>) -> Self {
Dict {
map: HashMap::default(),
alphabet: charslice(alphabet),
}
}
pub fn new_ascii_lowercase() -> Self {
Dict::new(ASCII_LOWERCASE)
}
pub fn correction(&self, word: impl AsRef<str>) -> Option<String> {
let k = word.as_ref();
if self.map.contains_key(k) {
Some(k.to_string())
} else if let Some(dist_1_correction) = word
.dist1edits(&self.alphabet)
.filter(|x| self.map.contains_key(x))
.max_by_key(|x| self.map[x])
{
Some(dist_1_correction)
} else {
word.dist2edits(&self.alphabet)
.filter(|x| self.map.contains_key(x))
.max_by_key(|x| self.map[x])
}
}
pub fn insert(&mut self, word: impl AsRef<str>) {
if let Some(v) = self.map.get_mut(word.as_ref()) {
*v += 1;
return;
}
self.map.insert(word.as_ref().to_string(), 1);
}
pub fn from_corpus<I>(corpus: I, alphabet: impl AsRef<str>) -> Self
where
I: IntoIterator,
I::Item: AsRef<str>,
{
let mut count: HashMap<String, usize> = HashMap::new();
for k in corpus.into_iter() {
if let Some(v) = count.get_mut(k.as_ref()) {
*v += 1;
continue;
}
count.insert(k.as_ref().to_string(), 1);
}
Dict {
map: count,
alphabet: charslice(alphabet),
}
}
pub fn save_to_file<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
self.save_to_writer(io::BufWriter::new(File::create(path)?))
}
pub fn save_to_writer(&self, mut w: impl io::Write) -> io::Result<()> {
let mut buf: Vec<_> = self.map.iter().collect();
buf.sort_by(|(k0, v0), (k1, v1)| v1.cmp(v0).then_with(|| k0.cmp(k1)));
for (k, v) in buf {
writeln!(w, "{} {}", k, v)?
}
Ok(())
}
pub fn load_from_file<P: AsRef<Path>>(path: P, alphabet: impl AsRef<str>) -> Result<Self> {
Dict::load_from_reader(&mut io::BufReader::new(File::open(path)?), alphabet)
}
pub fn load_from_reader(r: impl io::BufRead, alphabet: impl AsRef<str>) -> Result<Self> {
Ok(Dict {
map: r
.lines()
.enumerate()
.map(|(i, line_res)| {
let line = line_res?;
let mut split = line.split_whitespace();
match (split.next(), split.next()) {
(Some(word), Some(count)) => match count.parse::<usize>() {
Err(err) => Err(IOError::ParseInt(i, err)),
Ok(count) => Ok((word.to_string(), count)),
},
_ => Err(IOError::BadFormat(i)),
}
})
.collect::<Result<HashMap<String, usize>>>()?,
alphabet: charslice(alphabet),
})
}
}
impl From<io::Error> for IOError {
fn from(err: io::Error) -> Self {
IOError::IO(err)
}
}
impl<S: AsRef<str>> std::iter::Extend<S> for Dict {
fn extend<I: IntoIterator<Item = S>>(&mut self, it: I) {
for s in it {
self.insert(s)
}
}
}
impl std::fmt::Display for IOError {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
IOError::IO(err) => err.fmt(f),
IOError::ParseInt(line, err) => {
write!(f, "error parsing count of word on line {}: {}", line, err)
}
IOError::BadFormat(line) => write!(f, "could not parse line {}", line),
}
}
}
impl std::error::Error for IOError {}
impl<'a, Q: ?Sized> std::ops::Index<&'a Q> for Dict
where
String: Borrow<Q>,
Q: Eq + Hash,
{
type Output = usize;
fn index(&self, q: &Q) -> &usize {
if let Some(v) = self.get(q) {
v
} else {
&0
}
}
}