Advertisement
nikolov_k

CountWords

Jan 30th, 2013
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.21 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Text.RegularExpressions;
  5. using System.Linq;
  6.  
  7.  
  8. class words
  9. {
  10.     public string Text { set; get; }
  11.     public int Count { set; get; }
  12. }
  13.  
  14.  
  15. class RemoveWords
  16. {
  17.     static void Main()
  18.     {
  19.         try
  20.         {
  21.             StreamReader readerWord = new StreamReader("..//..//words.txt");
  22.             StreamReader readerInput = new StreamReader("..//..//test.txt");
  23.             StreamWriter writer = new StreamWriter("..//..//result.txt");
  24.             List<words> wordList = new List<words>();
  25.             using (readerWord)
  26.             {
  27.                 string line = readerWord.ReadLine();
  28.                 while (line != null)
  29.                 {
  30.                     words word = new words();
  31.                     word.Count = 0;
  32.                     word.Text = line;
  33.                     wordList.Add(word);
  34.                     line = readerWord.ReadLine();
  35.                 }
  36.             }
  37.             using (readerInput)
  38.             {
  39.                 string line = readerInput.ReadLine();
  40.                 while (line != null)
  41.                 {
  42.                     for (int i = 0; i < wordList.Count; i++)
  43.                     {
  44.                         int count = Regex.Matches(line, "\\b" + wordList[i].Text + "\\b").Count;
  45.                         wordList[i].Count += count;
  46.                     }
  47.                     line = readerInput.ReadLine();
  48.                 }
  49.             }
  50.             List<words> ordered = wordList.OrderByDescending(a => a.Count).ToList();
  51.             using (writer)
  52.             {
  53.                 foreach (var word in ordered)
  54.                 {
  55.                     writer.WriteLine(word.Text);
  56.                 }
  57.             }
  58.         }
  59.         catch (DirectoryNotFoundException)
  60.         {
  61.             Console.WriteLine("Directory not found");
  62.         }
  63.         catch (FileNotFoundException)
  64.         {
  65.             Console.WriteLine("File not found");
  66.         }
  67.         catch (IOException)
  68.         {
  69.             Console.WriteLine("IO Exception");
  70.         }
  71.  
  72.         catch (UnauthorizedAccessException)
  73.         {
  74.             Console.WriteLine("Unauthorized Access");
  75.         }
  76.     }
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement