Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- namespace WordFrequencyFinder
- {
- class Program
- {
- static async Task Main(string[] args)
- {
- if (args.Length < 2)
- {
- Console.WriteLine("Usage: WordFrequencyFinder <directory path> <min word length>");
- return;
- }
- string directoryPath = args[0];
- if (!int.TryParse(args[1], out int minWordLength))
- {
- Console.WriteLine("Invalid minimum word length.");
- return;
- }
- if (!Directory.Exists(directoryPath))
- {
- Console.WriteLine("Directory does not exist.");
- return;
- }
- var wordFrequency = await GetWordFrequenciesAsync(directoryPath, minWordLength);
- var topWords = wordFrequency.OrderByDescending(kvp => kvp.Value).Take(10);
- Console.WriteLine("Top-10 most used words:");
- foreach (var word in topWords)
- {
- Console.WriteLine($"{word.Key}: {word.Value}");
- }
- }
- static async Task<ConcurrentDictionary<string, int>> GetWordFrequenciesAsync(string directoryPath, int minWordLength)
- {
- var wordFrequency = new ConcurrentDictionary<string, int>();
- var files = Directory.GetFiles(directoryPath, "*.txt");
- var tasks = files.Select(file => ProcessFileAsync(file, minWordLength, wordFrequency)).ToArray();
- await Task.WhenAll(tasks);
- return wordFrequency;
- }
- static async Task ProcessFileAsync(string filePath, int minWordLength, ConcurrentDictionary<string, int> wordFrequency)
- {
- var content = await File.ReadAllTextAsync(filePath);
- var words = Regex.Split(content.ToLowerInvariant(), @"\W+")
- .Where(word => word.Length >= minWordLength);
- foreach (var word in words)
- {
- wordFrequency.AddOrUpdate(word, 1, (key, oldValue) => oldValue + 1);
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment