Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.IO;
- using System.Linq;
- using System.Collections.Generic;
- namespace WordCount
- {
- class Program
- {
- static void Main()
- {
- StreamReader wordReader = new StreamReader("words.txt");
- Dictionary<string, int> wordsCounter = new Dictionary<string, int>();
- //add the words to count in a dictionary
- using (wordReader)
- {
- string word = wordReader.ReadLine();
- while (word != null)
- {
- wordsCounter.Add(word, 0);
- word = wordReader.ReadLine();
- }
- }
- StreamReader textReader = new StreamReader("text.txt");
- //read the text
- //lazy to write, so I remove all punctuation marks I saw and put the words in an array
- using (textReader)
- {
- string[] text = textReader.ReadToEnd()
- .Split(new char[] { ' ','.',',','?','!', '-'}, StringSplitOptions.RemoveEmptyEntries);
- for (int i = 0; i < text.Length; i++)
- {
- if (wordsCounter.ContainsKey(text[i].ToLower()))
- {
- wordsCounter[text[i].ToLower()]++; //counting occurrence of the word case insensitive
- }
- }
- //write the dictionary in a new file
- FileStream file = new FileStream("actualResult.txt", FileMode.Create);
- var writer = new StreamWriter(file);
- writer.AutoFlush = true;
- foreach (var item in wordsCounter)
- {
- writer.WriteLine(item.Key + " - " + item.Value);
- }
- }
- //print sorted dictionary on console
- foreach (var item in wordsCounter
- .OrderByDescending(x => x.Value))
- {
- Console.WriteLine($"{item.Key} - {item.Value}");
- }
- }
- }
- }
Add Comment
Please, Sign In to add comment