Skip to content

Instantly share code, notes, and snippets.

@Soulstorm50
Created March 12, 2017 10:28
Show Gist options
  • Save Soulstorm50/637e5f0c79bf21efece8b5d953eed55c to your computer and use it in GitHub Desktop.
Save Soulstorm50/637e5f0c79bf21efece8b5d953eed55c to your computer and use it in GitHub Desktop.
C# топ-50 самых популярных слов в txt
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace ConsoleApplication4
{
public class Word
{
public int Count { get; set; }
public string WordItem { get; set; }
}
public static class StringExt
{
public static List<string> ToSplittedList(this string s)
{
Regex regex = new Regex(@"[0-9\n\r]");
if (s.Length != 0)
{
s = regex.Replace(s, "");
return
s.Replace(",", " ")
.Replace(".", " ")
.Replace("!", " ")
.Replace(" ", " ")
.ToLower()
.Split(' ')
.ToList();
}
return null;
}
}
public static class FileUtils
{
public static string LoadData(string name)
{
string data;
try
{
data = File.ReadAllText(name);
}
catch (Exception)
{
throw new Exception("Не удалось загрузить файл. Файл существует?");
}
return data;
}
internal static object LoadData(string v, Encoding encoding)
{
throw new NotImplementedException();
}
}
class Program
{
private static List<Word> _list = new List<Word>();
private static void Main(string[] args)
{
var textData = FileUtils.LoadData(@"D:\Soulstorm\WarAndPeace.txt");
var wordListItems = textData.ToSplittedList();
foreach (var wordListItem in wordListItems)
{
if (_list.Any(word => word.WordItem == wordListItem))
{
_list.Single(word => word.WordItem == wordListItem).Count++;
}
else
{
_list.Add(new Word()
{
Count = 1,
WordItem = wordListItem
});
}
}
Console.WriteLine("Топ 50 слов текста");
var words = _list.OrderByDescending(word => word.Count).ToList();
for (int i = 0; i <= 50; i++)
{
Console.WriteLine(string.Format("{0} - встречается {1} раз", words[i].WordItem, words[i].Count));
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment