Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Text.RegularExpressions;
- using System.Security;
- using System.Linq;
- //Write a program that reads a list of words from a file words.txt and finds how many times each of
- //the words is contained in another file test.txt. The result should be written in the file
- //result.txt and the words should be sorted by the number of their occurrences in descending order.
- //Handle all possible exceptions in your methods.
- class RemoveWords
- {
- static void Main()
- {
- try
- {
- Dictionary<string, int> words = new Dictionary<string, int>();
- using (StreamReader reader = new StreamReader("words.txt"))
- {
- ReadWords(reader, words);
- }
- using (StreamReader reader = new StreamReader("test.txt"))
- using (StreamWriter writer = new StreamWriter("result.txt"))
- {
- CountMatches(reader, words);
- WriteWords(words, writer);
- }
- }
- catch (FileNotFoundException err)
- {
- Console.WriteLine(err.Message);
- }
- catch (DirectoryNotFoundException err)
- {
- Console.WriteLine(err.Message);
- }
- catch (IOException err)
- {
- Console.WriteLine(err.Message);
- }
- catch (UnauthorizedAccessException err)
- {
- Console.WriteLine(err.Message);
- }
- catch (ArgumentNullException err)
- {
- Console.WriteLine(err.Message);
- }
- catch (ArgumentException err)
- {
- Console.WriteLine(err.Message);
- }
- catch (OutOfMemoryException err)
- {
- Console.WriteLine(err.Message);
- }
- catch (NotSupportedException err)
- {
- Console.WriteLine(err.Message);
- }
- catch (SecurityException err)
- {
- Console.WriteLine(err.Message);
- }
- catch (RegexMatchTimeoutException err)
- {
- Console.WriteLine(err.Message);
- }
- }
- private static void WriteWords(Dictionary<string, int> words, StreamWriter writer)
- {
- var sortedWords = (from entry in words orderby entry.Value descending select entry).ToDictionary(pair => pair.Key, pair => pair.Value);
- foreach (var item in sortedWords)
- {
- writer.WriteLine(item.Key + " " + item.Value);
- }
- }
- private static void CountMatches(StreamReader reader, Dictionary<string, int> words)
- {
- List<string> keys = new List<string>(words.Keys);
- string line;
- while ((line = reader.ReadLine()) != null)
- {
- foreach (string key in keys)
- {
- words[key] += Regex.Matches(line, "\\b" + key + "\\b").Count;
- }
- }
- }
- private static void ReadWords(StreamReader reader, Dictionary<string, int> words)
- {
- string line;
- while ((line = reader.ReadLine()) != null)
- {
- string[] word = line.Split();
- foreach (string item in word)
- {
- words.Add(item, 0);
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment