nahidjamalli

Task based version #1

Jul 23rd, 2024
188
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.08 KB | None | 0 0
  1. namespace WordFrequencyFinder
  2. {
  3.     class Program
  4.     {
  5.         static async Task Main(string[] args)
  6.         {
  7.             if (args.Length < 2)
  8.             {
  9.                 Console.WriteLine("Usage: WordFrequencyFinder <directory path> <min word length>");
  10.                 return;
  11.             }
  12.  
  13.             string directoryPath = args[0];
  14.             if (!int.TryParse(args[1], out int minWordLength))
  15.             {
  16.                 Console.WriteLine("Invalid minimum word length.");
  17.                 return;
  18.             }
  19.  
  20.             if (!Directory.Exists(directoryPath))
  21.             {
  22.                 Console.WriteLine("Directory does not exist.");
  23.                 return;
  24.             }
  25.  
  26.             var wordFrequency = await GetWordFrequenciesAsync(directoryPath, minWordLength);
  27.             var topWords = wordFrequency.OrderByDescending(kvp => kvp.Value).Take(10);
  28.  
  29.             Console.WriteLine("Top-10 most used words:");
  30.             foreach (var word in topWords)
  31.             {
  32.                 Console.WriteLine($"{word.Key}: {word.Value}");
  33.             }
  34.         }
  35.  
  36.         static async Task<ConcurrentDictionary<string, int>> GetWordFrequenciesAsync(string directoryPath, int minWordLength)
  37.         {
  38.             var wordFrequency = new ConcurrentDictionary<string, int>();
  39.             var files = Directory.GetFiles(directoryPath, "*.txt");
  40.  
  41.             var tasks = files.Select(file => ProcessFileAsync(file, minWordLength, wordFrequency)).ToArray();
  42.             await Task.WhenAll(tasks);
  43.  
  44.             return wordFrequency;
  45.         }
  46.  
  47.         static async Task ProcessFileAsync(string filePath, int minWordLength, ConcurrentDictionary<string, int> wordFrequency)
  48.         {
  49.             var content = await File.ReadAllTextAsync(filePath);
  50.             var words = Regex.Split(content.ToLowerInvariant(), @"\W+")
  51.                              .Where(word => word.Length >= minWordLength);
  52.  
  53.             foreach (var word in words)
  54.             {
  55.                 wordFrequency.AddOrUpdate(word, 1, (key, oldValue) => oldValue + 1);
  56.             }
  57.         }
  58.     }
  59. }
Advertisement
Add Comment
Please, Sign In to add comment