rust
28 lines · 7 steps
Counting and ranking words in Rust
Tally word frequencies into a HashMap, then sort them to surface the most common terms.
Explained by
highlit
1use std::collections::HashMap;
2
3pub fn word_frequencies(text: &str) -> HashMap<String, usize> {
4 let mut counts: HashMap<String, usize> = HashMap::new();
5
6 for word in text.split_whitespace() {
7 let normalized: String = word
8 .chars()
9 .filter(|c| c.is_alphanumeric())
10 .flat_map(|c| c.to_lowercase())
11 .collect();
12
13 if normalized.is_empty() {
14 continue;
15 }
16
17 *counts.entry(normalized).or_insert(0) += 1;
18 }
19
20 counts
21}
22
23pub fn top_words(text: &str, limit: usize) -> Vec<(String, usize)> {
24 let mut ranked: Vec<(String, usize)> = word_frequencies(text).into_iter().collect();
25 ranked.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
26 ranked.truncate(limit);
27 ranked
28}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1The entry API lets you read-or-initialize a map slot in one branchless expression.
- 2Normalizing tokens before counting keeps casing and punctuation from fragmenting your tallies.
- 3A tie-breaker comparator gives sorts a deterministic, predictable order.
Related explainers
rust
use axum::{extract::{Path, State}, http::StatusCode, Json}; use dashmap::DashMap; use serde::Serialize; use std::sync::Arc;
Request coalescing in an Axum handler
caching
concurrency
request-coalescing
Advanced
8 steps
rust
use std::net::Ipv4Addr; use std::str::FromStr; #[derive(Debug, Clone, Copy)]
Parsing and matching IPv4 CIDR ranges in Rust
bitwise-operations
parsing
error-handling
Intermediate
8 steps
rust
use std::sync::OnceLock; static CRC_TABLE: OnceLock<[u32; 256]> = OnceLock::new();
Table-driven CRC32 with lazy init in Rust
checksums
lazy-initialization
lookup-tables
Intermediate
8 steps
rust
use axum::{ body::Body, extract::Path, http::{header, HeaderMap, HeaderValue, StatusCode},
HTTP range requests for video streaming in Axum
http-range-requests
streaming
async-io
Advanced
8 steps
rust
use std::sync::mpsc; use std::thread; use std::time::Duration;
Running work with a timeout in Rust
concurrency
channels
timeout
Intermediate
7 steps
rust
use axum::{extract::State, response::IntoResponse, Json}; use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; use std::sync::Arc;
Building a JSON-RPC 2.0 handler in Axum
json-rpc
serde
request-dispatch
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/counting-and-ranking-words-in-rust-explained-rust-11f0/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.