AzLearn

تمرين إعادة البناء

Word Frequency Counter

أعد كتابة برنامج Rust يحسب أكثر الكلمات تكراراً من ملف نصي أو الإدخال القياسي.

rust ~14 دقيقة مبتدئ
أعد بناء الكود Rebuild

هذا هو الكود. اكتبه بنفسك.

الكود المرجعي
use std::collections::HashMap;
use std::env;
use std::fs;
use std::io::{self, Read};

fn main() -> io::Result<()> {
    let text = match env::args().nth(1) {
        Some(path) => fs::read_to_string(path)?,
        None => {
            let mut input = String::new();
            io::stdin().read_to_string(&mut input)?;
            input
        }
    };

    let mut counts = HashMap::new();

    // طبّع الكلمات قبل العد — Normalize words before counting
    for word in text.split_whitespace() {
        let cleaned = word
            .trim_matches(|ch: char| !ch.is_alphanumeric())
            .to_lowercase();

        if !cleaned.is_empty() {
            *counts.entry(cleaned).or_insert(0usize) += 1;
        }
    }

    let mut pairs: Vec<_> = counts.into_iter().collect();
    pairs.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));

    for (word, count) in pairs.into_iter().take(10) {
        println!("{word}: {count}");
    }

    Ok(())
}
اكتب هنا