using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;
namespace tstRegex
{
class Program
{
static void Main(string[] args)
{
Console.Write("Enter File Name with Extension :");
string sFileName = Console.ReadLine();
Console.Write("Enter File Path :");
string sPath = Console.ReadLine();
Console.WriteLine();
FileInfo fi = new FileInfo(Path.Combine (sPath,sFileName));
if (!fi.Exists)
{
Console.WriteLine("No input file found");
Console.ReadLine();
return;
}
SortedDictionary occurrences = new SortedDictionary();
using (StreamReader reader = new StreamReader(fi.FullName))
{
string line = reader.ReadToEnd();
//the word is splited with white space,comma,dot.
//you can add any other delimeter if needed
string[] words = Regex.Split(line, @"[ .,\s]");
foreach (string word in words)
{
if (occurrences.ContainsKey(word.ToLower()) || string.IsNullOrEmpty(word))
continue;
string pattern = string.Format("{0}{1}{0}", @"\b", word); //to get whole word matched
MatchCollection col = Regex.Matches(line, pattern, RegexOptions.IgnoreCase);
occurrences.Add(word.ToLower(), col.Count);
}
}
var results = occurrences.OrderByDescending(x => x.Value);
int i = 1;
foreach (KeyValuePair result in results )
{
Console.WriteLine("{0} Occurs {1} times ",result.Key,result.Value);
if (i++ ==3 ) break;
}
Console.ReadLine();
}
}
}
|