Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* Write a program that reads a list of words from the file words.txt and finds how many times each of the words is contained in another file text.txt. Matching should be case-insensitive.
- * Write the results in file results.txt. Sort the words by frequency in descending order. Use StreamReader in combination with StreamWriter. */
- namespace _03.Word_Count
- {
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Text;
- using System.Text.RegularExpressions;
- class WordCount
- {
- const string Pattern = @"\b[\w']+\b";
- static void Main(string[] args)
- {
- string words = string.Empty;
- var reader = new StreamReader("../../words.txt");
- using (reader)
- {
- words = reader.ReadToEnd();
- }
- string text = string.Empty;
- using (reader = new StreamReader("../../text.txt"))
- {
- text = reader.ReadToEnd();
- }
- Dictionary<string, int> wordsCount = new Dictionary<string, int>();
- MatchCollection matches1 = Regex.Matches(words, Pattern);
- MatchCollection matches2 = Regex.Matches(text, Pattern);
- foreach (Match word in matches1)
- {
- foreach (Match match in matches2)
- {
- if (word.ToString().ToLower() == match.ToString().ToLower())
- {
- if (!wordsCount.ContainsKey(word.ToString()))
- {
- wordsCount[word.ToString()] = 0;
- }
- wordsCount[word.ToString()]++;
- }
- }
- }
- List<KeyValuePair<string, int>> keyValuePairs = wordsCount
- .OrderByDescending(p => p.Value).ToList();
- using (var stream = new FileStream("../../result.txt", FileMode.Create))
- {
- using (var writer = new StreamWriter(stream, Encoding.ASCII, 4096))
- {
- foreach (var pair in keyValuePairs)
- {
- writer.WriteLine("{0} - {1}", pair.Key, pair.Value);
- }
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement