Last active
June 30, 2020 13:51
-
-
Save grishace/997f767d6e60fafd6b79de113940bebd to your computer and use it in GitHub Desktop.
Words frequency with LINQ
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var str = "The quick brown fox jumped over the lazy dog. Hello-world! wOrLd WorLd. The new order!"; | |
var words = | |
new Regex(@"\b([A-Z-]+)\b", RegexOptions.IgnoreCase) | |
.Matches(str) | |
.Select(m => m.Groups[0].Value.ToLower()) | |
.GroupBy(g => g) | |
.Select(g => KeyValuePair.Create(g.Key, g.Count())) | |
.OrderByDescending(kv => kv.Value) | |
.ToDictionary(kv => kv.Key, kv => kv.Value); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private static readonly Regex word = new Regex(@"\b([a-z]+)\b", RegexOptions.IgnoreCase | RegexOptions.Compiled); | |
static void Main(string[] args) | |
{ | |
File.ReadAllLines("WordFile.txt") | |
.SelectMany(s => word.Matches(s).Select(m => m.Groups[0].Value)) | |
.GroupBy(w => w.ToLowerInvariant()) | |
.Select(g => Tuple.Create(g.Key, g.Count())) | |
.OrderByDescending(t => t.Item2) | |
.Take(20) | |
.Select(t => t.Item1) | |
.ToList() | |
.ForEach(Console.WriteLine); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment