Advertisement
Guest User

03. Word Count

a guest
Jan 28th, 2024
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.79 KB | Source Code | 0 0
  1. using System.Text.RegularExpressions;
  2.  
  3. namespace WordCount
  4. {
  5.     public class WordCount
  6.     {
  7.         static void Main()
  8.         {
  9.             string wordPath = @"..\..\..\Files\words.txt";
  10.             string textPath = @"..\..\..\Files\text.txt";
  11.             string outputPath = @"..\..\..\Files\output.txt";
  12.  
  13.             CalculateWordCounts(wordPath, textPath, outputPath);
  14.         }
  15.  
  16.         public static void CalculateWordCounts(string wordsFilePath, string textFilePath, string outputFilePath)
  17.         {
  18.             using (StreamReader wordReader = new StreamReader(wordsFilePath))
  19.             {
  20.                 using (StreamReader textReader = new StreamReader(textFilePath))
  21.                 {
  22.                     using (StreamWriter writerOut = new StreamWriter(outputFilePath))
  23.                     {
  24.                         Dictionary<string, int> counts = new Dictionary<string, int>();
  25.  
  26.                         string[] words = wordReader.ReadLine().ToLower().Split();
  27.                         string text = textReader.ReadToEnd().ToLower();
  28.  
  29.                         foreach (string word in words)
  30.                         {
  31.                             string pattern = string.Format(@"\b{0}\b", word);
  32.                             MatchCollection matches = Regex.Matches(text, pattern);
  33.  
  34.                             if (!counts.ContainsKey(word))
  35.                             {
  36.                                 counts[word] = matches.Count;
  37.                             }
  38.                         }
  39.  
  40.                         foreach (var (key, value) in counts.OrderByDescending(x => x.Value))
  41.                         {
  42.                             writerOut.WriteLine($"{key} - {value}");
  43.                         }
  44.                     }
  45.                 }
  46.             }
  47.         }
  48.     }
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement