docs

你正在阅读 v0.1.2 的文档。Nabi 0.1.2 已不再提供支持。 最新版本:v0.1.3 →

本页尚未翻译,以下为英文原文。

#Word count

本页内容

Count the lines, words and characters of a text, then use a Dict and sorting to pick the five most frequent words.

#Code

#Walkthrough

  • Iterators on str do the counting. lines() yields lines, split_whitespace() yields words, and count() counts them. The character count is char_count(), not the byte length len() (Strings, str methods).
  • normalize builds the word in a StrBuf one character at a time, dropping punctuation and lowercasing, so "Dog," and "dog." count as the same word (StrBuf).
  • The frequency table is a Dict<str, i32>. counts[w, default: 0] += 1 stores 0 first when w is missing, then adds one (Collections and iterators, Dict).
  • sorted_by_key on the dictionary gives its (word, count) pairs as a sorted list. The key (-c, w) puts the highest count first and breaks ties alphabetically, so the output is always the same; take(n).to_list() keeps the first n. enumerate(start: 1) numbers the ranks from 1 (Collections and iterators).
  • The table is aligned with f-string format specs: {w:<6} left-aligns, {c:>2} right-aligns (2.10.8 align and width).

Found a mistake? Edit this page on GitHub. Last updated