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
|
use std::env;
use std::fs::File;
use std::io;
use std::io::BufRead;
use std::ops;
use std::collections::HashMap;
fn main() -> io::Result<()> {
for filename in env::args().skip(1) {
let mut f = File::open(&filename)?;
let mut reader = io::BufReader::new(f);
let counts = count_words(&mut reader)?;
counts.print()
}
Ok(())
}
fn count_words(reader: &mut io::BufReader<File>) -> io::Result<WordCounts> {
let mut counts = WordCounts::new();
for line in reader.lines() {
let line = line?;
counts += count_words_in_line(&line);
}
Ok(counts)
}
fn count_words_in_line(line: &str) -> WordCounts {
let mut counts = WordCounts::new();
let mut word = String::new();
for c in line.chars() {
if c.is_alphabetic() {
word.push(c);
} else {
if !word.is_empty() {
counts.count(word.clone());
word.clear();
}
}
}
if !word.is_empty() {
counts.count(word.clone());
}
counts
}
struct WordCounts {
counts: HashMap<String, u32>,
}
impl WordCounts {
fn new() -> Self {
WordCounts {
counts: HashMap::new(),
}
}
fn count(&mut self, word: String) {
self.add(word, 1);
}
fn add(&mut self, word: String, count: u32) {
let counter = self.counts.entry(word).or_insert(0);
*counter += count;
}
fn print(&self) {
for (word, count) in self.counts.iter() {
println!("{} {}", count, word);
}
}
}
impl ops::AddAssign for WordCounts {
fn add_assign(&mut self, other: WordCounts) {
for (word, count) in other.counts.iter() {
self.add(word.to_string(), *count);
}
}
}
|