var text = "test the text test on test platform";
var words = text.Split(' ');
var stat = words.Distinct().ToDictionary(word => word, word => words.Count(x => x == word));
foreach (var (key, value) in stat) Debug.WriteLine($"Word: {key} count: {value}");
Как найти самое часто используемое слово в тексте?
Здравствуйте! Как найти самое часто используемое слово в тексте на C#? Какие могут быть подходы в решении задачи?
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
for (int i = 0; i < 1000000; i++)
{
var words = Regex.Matches(text, "(\\w+)");
}
TimeSpan ts = stopWatch.Elapsed;
string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
ts.Hours, ts.Minutes, ts.Seconds,
ts.Milliseconds / 10);
Debug.WriteLine("RunTime " + elapsedTime);Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
for (int i = 0; i < 1000000; i++)
{
var words = text.Split(' ');
}
TimeSpan ts = stopWatch.Elapsed;
string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
ts.Hours, ts.Minutes, ts.Seconds,
ts.Milliseconds / 10);
Debug.WriteLine("RunTime " + elapsedTime);
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
for (int i = 0; i < 1000000; i++)
{
var words = text.Split(new []{' ', ',', ';', ':', '.', '?', '!'});
}
TimeSpan ts = stopWatch.Elapsed;
string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
ts.Hours, ts.Minutes, ts.Seconds,
ts.Milliseconds / 10);
Debug.WriteLine("RunTime " + elapsedTime);
using System;
using System.Diagnostics;
using System.Linq;
using System.Text.RegularExpressions;
namespace regex_or_not
{
class Program
{
static void Main(string[] args)
{
var text = "test the text test on test platform";
var sw = new Stopwatch();
sw.Start();
var words = text.Split(' ');
var stat = words.Distinct().ToDictionary(word => word, word => words.Count(x => x == word));
foreach (var (key, value) in stat)
Console.WriteLine($"Word: {key} count: {value}");
Console.WriteLine($"Real Job RunTime {sw.Elapsed:G}");
sw.Reset();
sw.Start();
var d = new[] { ' ', ',', ';', ':', '.', '?', '!' };
foreach (var w in text.Split(d))
Console.WriteLine('\t' + w);
Console.WriteLine($"Split RunTime {sw.Elapsed:G}");
sw.Reset();
sw.Start();
foreach (var w in Regex.Matches(text, "(\\w+)"))
Console.WriteLine('\t' + w.ToString());
Console.WriteLine($"RegEx RunTime {sw.Elapsed:G}");
sw.Reset();
}
}
}