Skip to content

Count the most common words

Read text, count each word, and print the most frequent ones. A Map counts, and sorting by count (then by word, so ties come out the same every time) picks the top.

let text = "the cat sat on the mat. The cat saw the dog, and the dog ran."
let mut counts: Map<Str, i64> = Map.new()
for raw in text.words() {
let word = raw.to_lower().replace(".", "").replace(",", "")
let now = counts.get(word.clone()).unwrap_or(&0) + 1
counts.insert(word, now)
}
let mut ranked: Vec<(i64, Str)> = []
for (word, n) in &counts {
ranked.push((0 - *n, word.clone()))
}
ranked.sort_by(fn(a: &(i64, Str), b: &(i64, Str)) -> i64 {
if a.0 != b.0 {
return a.0.compare(&b.0)
}
return a.1.compare(&b.1)
})
for (n, word) in ranked.slice(0, 3) {
print(f"{word:<5} {0 - n}")
}
the 5
cat 2
dog 2

To read the text from a file instead, use let text = try fs.read(&path) with import fs; to read standard input, import io and let text = io.read_all().