#단어 세기
텍스트의 줄, 단어, 문자 수를 세고 Dict와 정렬로 가장 자주 나오는 단어 다섯 개를 고릅니다.
#코드
nabi
// Count lines, words and chars, then list the most frequent words.
const TEXT: str = "The quick brown fox jumps over the lazy dog.
The dog sleeps; the fox does not.
A fox, a dog, and the long summer day.
Quick thinking wins the day!";
struct Stats {
lines: usize;
words: usize;
chars: usize;
}
fn stats(text: str) -> Stats {
let s = Stats { lines: 0, words: 0, chars: text.char_count() };
for line in text.lines() {
s.lines += 1;
s.words += line.split_whitespace().count();
}
s
}
// Lowercase a token and drop surrounding punctuation ("Dog," -> "dog").
fn normalize(token: str) -> str {
let sb = StrBuf::new();
for c in token.chars() {
if c.is_alphanumeric() || c == '\'' {
sb.push_str(c.to_lowercase());
}
}
sb.to_str()
}
fn frequencies(text: str) -> Dict<str, i32> {
let counts: Dict<str, i32> = Dict::new();
for token in text.split_whitespace() {
let w = normalize(token);
if w.is_empty() { continue; }
counts[w, default: 0] += 1;
}
counts
}
fn top(counts: Dict<str, i32>, n: usize) -> List<(str, i32)> {
// Most frequent first; ties broken alphabetically so output is stable.
counts.sorted_by_key(|(w, c)| (-c, w)).take(n).to_list()
}
fn main() {
let s = stats(TEXT);
println(f"lines {s.lines:>4}");
println(f"words {s.words:>4}");
println(f"chars {s.chars:>4}");
let counts = frequencies(TEXT);
println(f"\n{counts.len()} distinct words, top 5:");
for (rank, (w, c)) in top(counts, 5).enumerate(start: 1) {
let bar = "#".repeat(c as usize);
println(f"{rank}. {w:<6} {c:>2} {bar}");
}
}
lines 5
words 30
chars 147
18 distinct words, top 5:
1. the 6 ######
2. dog 3 ###
3. fox 3 ###
4. a 2 ##
5. day 2 ##
#설명
- 세는 일은
str의 반복자가 맡습니다.lines()는 줄을,split_whitespace()는 단어를 내고,count()가 그 수를 셉니다. 문자 수는 바이트 길이len()이 아니라char_count()입니다(문자열,str메서드). normalize는 구두점을 버리고 소문자로 바꾸면서StrBuf에 한 글자씩 단어를 만듭니다. 그래서"Dog,"와"dog."는 같은 단어로 셉니다(StrBuf).- 빈도 표는
Dict<str, i32>입니다.counts[w, default: 0] += 1은w가 없으면 먼저0을 넣고 하나를 더합니다(컬렉션과 반복자,Dict). - 사전에
sorted_by_key를 쓰면(word, count)쌍이 정렬된 리스트로 나옵니다. 키(-c, w)는 개수가 많은 것을 앞에 두고 개수가 같으면 알파벳순으로 정하므로 출력은 언제나 같습니다.take(n).to_list()가 앞의n개를 남깁니다.enumerate(start: 1)은 순위를 1부터 셉니다(컬렉션과 반복자). - 표는 f-string 포맷 지정자로 정렬합니다.
{w:<6}은 왼쪽 정렬,{c:>2}는 오른쪽 정렬입니다(2.10.8 정렬과 폭).
잘못된 곳이 있나요? GitHub에서 이 페이지 고치기. 마지막 수정