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
argscarries the command line; bad usage exits with code 1.File.ReadLinesstreams;GetValueOrDefaultmakes the tally one line.OrderByDescending(...).ThenBy(...).Take(10)shapes the report.
Keywords and builtins used here
foreachifinintnewstringvar
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.
Step 1 of 2 in Encore, step 28 of 29 in Language basics.