-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProgram.cs
72 lines (64 loc) · 2.14 KB
/
Program.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/* PROGRAM - main program */
using System;
using System.IO;
using System.Text;
using System.Linq;
using System.Collections.Generic;
using System.Text.RegularExpressions;
// data types
using StringMap = System.Collections.Generic.Dictionary<string, string>;
using IntMap = System.Collections.Generic.Dictionary<string, int>;
namespace App
{
class Program {
// main function
static void Main(string[] args) {
IntMap count = new IntMap();
StringMap argm = GetArgs(args);
try {
StreamReader file = new StreamReader(argm[""]);
Regex find = new Regex(argm.ContainsKey("-p") ? argm["-p"] : @"\w+");
CountInFile(count, find, file);
ListCounts(count);
}
catch (Exception) { Console.WriteLine(GetHelp()); }
}
// display word counts
static void ListCounts(IntMap count) {
List<KeyValuePair<string, int>> o = count.ToList();
o.Sort((a, b) => b.Value.CompareTo(a.Value));
for (int i = 0; i < o.Count; i++)
Console.WriteLine(o[i].Key + new string(' ', o[i].Key.Length >= 80 ? 80 : 80 - o[i].Key.Length) + o[i].Value);
Console.WriteLine();
}
// update word counts from a file
static void CountInFile(IntMap count, Regex find, StreamReader file) {
string line;
while ((line = file.ReadLine()) != null)
CountInLine(count, find, line);
}
// update word counts from a line
static void CountInLine(IntMap count, Regex find, string line) {
foreach (Match word in find.Matches(line))
count[word.Value] = count.ContainsKey(word.Value)? count[word.Value]+1 : 1;
}
// get arguments to program
static StringMap GetArgs(string[] args) {
StringMap o = new StringMap();
string opt = "";
for (int i = 0; i < args.Length; i++) {
if (!args[i].StartsWith("-")) { o[opt] = args[i]; opt = ""; continue; }
if (opt != "") o[opt] = "";
opt = args[i];
}
return o;
}
// get usage help
static string GetHelp() {
StringBuilder str = new StringBuilder("ewordcount [-p <regex pattern>] <source file>\n");
str.Append("-p : specify regex pattern for items/words to be counted\n");
str.Append(" (e.g. -p gl\\w+, to look for gl calls in adb logs)\n");
return str.ToString();
}
}
}