typestar

word_freq.cs in C#

The word-count CLI in C#: stream a file, tally a dictionary, report a top ten.

// word_freq: count word frequencies in a file, print the top ten
if (args.Length != 1)
{
    Console.Error.WriteLine("usage: word_freq <file>");
    Environment.Exit(1);
}

var separators = new[] { ' ', '\t', '.', ',', ';', ':', '!', '?', '"' };
var counts = new Dictionary<string, int>();

foreach (var line in File.ReadLines(args[0]))
{
    var words = line.ToLower()
        .Split(separators, StringSplitOptions.RemoveEmptyEntries);
    foreach (var word in words)
    {
        counts[word] = counts.GetValueOrDefault(word) + 1;
    }
}

var report = counts.OrderByDescending(pair => pair.Value)
    .ThenBy(pair => pair.Key)
    .Take(10);

Console.WriteLine($"{counts.Count} distinct words");
foreach (var (word, count) in report)
{
    Console.WriteLine($"{count,5}  {word}");
}

How it works

  1. args carries the command line; bad usage exits with code 1.
  2. File.ReadLines streams; GetValueOrDefault makes the tally one line.
  3. OrderByDescending(...).ThenBy(...).Take(10) shapes the report.

Keywords and builtins used here

The run, in numbers

Lines
29
Characters to type
735
Tokens
179
Three-star pace
95 tpm

At the three-star pace of 95 tokens a minute, this run takes about 113 seconds.

Type this snippet

Step 1 of 2 in Encore, step 28 of 29 in Language basics.

← Previous Next →