实现说明
split_whitespace 统计词频可以归结为函数 main。
for word in text.split_whitespace() 承担全部的逐项处理。
使用要点
- 跑完文件,输出里会留下标记——
unique words:。
常见问题
运行「split_whitespace 统计词频」会打印什么?
不用做任何设置,直接把文件跑完——输出里的 unique words: 标签标明各步骤。
核心语句
for (word, count) in ranked.iter().take(3) {
println!("{count}x {word}");
}
let mut ranked: Vec<_> = counts.into_iter().collect();
代码示例
use std::collections::HashMap;
fn main() {
let text = "deploy the api deploy the worker restart the api and the worker";
// split_whitespace 是惰性迭代器,边遍历边统计,不先收集整个词表;
// 词是 &str,借用 text,无逐词分配
let mut counts: HashMap<&str, u32> = HashMap::new();
for word in text.split_whitespace() {
*counts.entry(word).or_insert(0) += 1;
}
// 聚合后按次数降序、同次数按单词升序:输出可复现
let mut ranked: Vec<_> = counts.into_iter().collect();
ranked.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(b.0)));
for (word, count) in ranked.iter().take(3) {
println!("{count}x {word}");
}
println!("unique words: {}", ranked.len());
}