Advertisement
dimipan80

Word Count

May 20th, 2015
278
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.32 KB | None | 0 0
  1. /* Write a program that reads a list of words from the file words.txt and finds how many times each of the words is contained in another file text.txt. Matching should be case-insensitive.
  2.  * Write the results in file results.txt. Sort the words by frequency in descending order. Use StreamReader in combination with StreamWriter. */
  3.  
  4. namespace _03.Word_Count
  5. {
  6.     using System.Collections.Generic;
  7.     using System.IO;
  8.     using System.Linq;
  9.     using System.Text;
  10.     using System.Text.RegularExpressions;
  11.  
  12.     class WordCount
  13.     {
  14.         const string Pattern = @"\b[\w']+\b";
  15.  
  16.         static void Main(string[] args)
  17.         {
  18.             string words = string.Empty;
  19.             var reader = new StreamReader("../../words.txt");
  20.             using (reader)
  21.             {
  22.                 words = reader.ReadToEnd();
  23.             }
  24.  
  25.             string text = string.Empty;
  26.             using (reader = new StreamReader("../../text.txt"))
  27.             {
  28.                 text = reader.ReadToEnd();
  29.             }
  30.  
  31.             Dictionary<string, int> wordsCount = new Dictionary<string, int>();
  32.             MatchCollection matches1 = Regex.Matches(words, Pattern);
  33.             MatchCollection matches2 = Regex.Matches(text, Pattern);
  34.             foreach (Match word in matches1)
  35.             {
  36.                 foreach (Match match in matches2)
  37.                 {
  38.                     if (word.ToString().ToLower() == match.ToString().ToLower())
  39.                     {
  40.                         if (!wordsCount.ContainsKey(word.ToString()))
  41.                         {
  42.                             wordsCount[word.ToString()] = 0;
  43.                         }
  44.  
  45.                         wordsCount[word.ToString()]++;
  46.                     }
  47.                 }
  48.             }
  49.  
  50.             List<KeyValuePair<string, int>> keyValuePairs = wordsCount
  51.                 .OrderByDescending(p => p.Value).ToList();
  52.  
  53.             using (var stream = new FileStream("../../result.txt", FileMode.Create))
  54.             {
  55.                 using (var writer = new StreamWriter(stream, Encoding.ASCII, 4096))
  56.                 {
  57.                     foreach (var pair in keyValuePairs)
  58.                     {
  59.                         writer.WriteLine("{0} - {1}", pair.Key, pair.Value);
  60.                     }
  61.                 }
  62.             }
  63.         }
  64.     }
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement