hi6tnikyt87

Untitled

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