3. May 2012
xhinker
DotNet
As the title indicates, the following code can calcuate words appearance frequence in a text file. to use this code,
1. run it and input a file name,
2. Press Enter, few seconds later, a result file will be created which contains the word frequence information.
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Input File Name:");
string fileName = Console.ReadLine();
string line;
Dictionary<string, long> wordDict = new Dictionary<string, long>();
System.IO.StreamReader file = new System.IO.StreamReader(fileName);
string[] tempWordArray;
string tempWord;
while ((line = file.ReadLine()) != null)
{
if (line.Trim() == "") continue;
line=line.Replace('?',' ');
line = line.Replace('.', ' ');
line = line.Replace(':', ' ');
tempWordArray = line.Split(' ');
for (int i=0; i < tempWordArray.Length; i++)
{
if (tempWordArray[i].Trim() == "") continue;
tempWord = tempWordArray[i].Trim().ToLower();
if (wordDict.ContainsKey(tempWord))
{
wordDict[tempWord] = wordDict[tempWord] + 1;
}
else
{
wordDict.Add(tempWord, 1);
}
}
}
file.Close();
var sortedDict = wordDict.OrderBy(x => x.Value);
System.IO.StreamWriter fileWriter =
new System.IO.StreamWriter(fileName+" result.txt");
string resultLine;
foreach (var item in sortedDict)
{
resultLine = item.Key + "\t\t\t" + item.Value;
Console.WriteLine(resultLine);
fileWriter.WriteLine(resultLine);
}
fileWriter.Flush();
fileWriter.Close();
Console.WriteLine("Total:"+wordDict.Count);
// Suspend the screen.
Console.ReadLine();
}
}