Counting Word Frequency (most significant words) i

2019-07-25 03:05发布

问题:

I would like to count the frequency of words (excluding some keywords) in a string and sort them DESC. So, how can i do it?

In the following string...

This is stackoverflow. I repeat stackoverflow.

Where the excluding keywords are

ExKeywords() ={"i","is"}

the output should be like

stackoverflow  
repeat         
this           

P.S. NO! I am not re-designing google! :)

回答1:

string input = "This is stackoverflow. I repeat stackoverflow.";
string[] keywords = new[] {"i", "is"};
Regex regex = new Regex("\\w+");

foreach (var group in regex.Matches(input)
    .OfType<Match>()
    .Select(c => c.Value.ToLowerInvariant())
    .Where(c => !keywords.Contains(c))
    .GroupBy(c => c)
    .OrderByDescending(c => c.Count())
    .ThenBy(c => c.Key))
{
    Console.WriteLine(group.Key);
}


回答2:

string s = "This is stackoverflow. I repeat stackoverflow.";
string[] notRequired = {"i", "is"};

var myData =
    from word in s.Split().Reverse()
    where (notRequired.Contains(word.ToLower()) == false)
    group word by word into g
    select g.Key;

foreach(string item in myData)
    Console.WriteLine(item);