yanass

WordCount - Streams - Code

Oct 9th, 2019
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.09 KB | None | 0 0
  1. using System;
  2. using System.IO;
  3. using System.Linq;
  4. using System.Collections.Generic;
  5.  
  6. namespace WordCount
  7. {
  8.     class Program
  9.     {
  10.         static void Main()
  11.         {
  12.             StreamReader wordReader = new StreamReader("words.txt");
  13.  
  14.             Dictionary<string, int> wordsCounter = new Dictionary<string, int>();
  15.  
  16.             //add the words to count in a dictionary
  17.             using (wordReader)
  18.             {
  19.                 string word = wordReader.ReadLine();
  20.  
  21.                 while (word != null)
  22.                 {
  23.                     wordsCounter.Add(word, 0);
  24.                     word = wordReader.ReadLine();
  25.                 }
  26.             }
  27.  
  28.             StreamReader textReader = new StreamReader("text.txt");
  29.  
  30.             //read the text
  31.             //lazy to write, so I remove all punctuation marks I saw and put the words in an array
  32.             using (textReader)
  33.             {
  34.                 string[] text = textReader.ReadToEnd()
  35.                     .Split(new char[] { ' ','.',',','?','!', '-'}, StringSplitOptions.RemoveEmptyEntries);
  36.  
  37.                 for (int i = 0; i < text.Length; i++)
  38.                 {                    
  39.                     if (wordsCounter.ContainsKey(text[i].ToLower()))
  40.                     {
  41.                         wordsCounter[text[i].ToLower()]++; //counting occurrence of the word case insensitive
  42.                     }
  43.                 }
  44.  
  45.                 //write the dictionary in a new file
  46.  
  47.                 FileStream file = new FileStream("actualResult.txt", FileMode.Create);
  48.                 var writer = new StreamWriter(file);
  49.                 writer.AutoFlush = true;
  50.  
  51.                 foreach (var item in wordsCounter)
  52.                 {
  53.                     writer.WriteLine(item.Key + " - " + item.Value);
  54.                 }
  55.             }
  56.            
  57.             //print sorted dictionary on console
  58.             foreach (var item in wordsCounter
  59.                 .OrderByDescending(x => x.Value))
  60.             {
  61.                 Console.WriteLine($"{item.Key} - {item.Value}");
  62.             }
  63.         }
  64.     }
  65. }
Add Comment
Please, Sign In to add comment