user560498
user560498

Reputation: 547

Get the number of word occurrences in text

Can this be done using C# Linq?

For example:

peter piper picked a pack of pickled peppers, the peppers were sweet and sower for peter, peter thought

Result:

peter 3
peppers 2
picked 1
...

I can do it with a nested for loop, but was thinking there is a more concise, resource light way using Linq.

Upvotes: 0

Views: 2590

Answers (5)

Tigran
Tigran

Reputation: 62248

"peter piper picked a pack of pickled peppers,the peppers 
were sweet and sower for peter, peter thought"
.Split(' ', ',').Count(x=>x == "peter");

The is for "peter", the same repeat for others.

Upvotes: 1

Reed Copsey
Reed Copsey

Reputation: 564323

You can use GroupBy:

string original = "peter piper picked a pack of pickled peppers, the peppers were sweet and sower for peter, peter thought";

var words = original.Split(new[] {' ',','}, StringSplitOptions.RemoveEmptyEntries);
var groups = words.GroupBy(w => w);

foreach(var item in groups)
    Console.WriteLine("Word {0}: {1}", item.Key, item.Count());

Upvotes: 6

Cristian Lupascu
Cristian Lupascu

Reputation: 40506

const string s = "peter piper picked a pack of pickled peppers, the peppers were sweet and sower for peter, peter thought";

var wordFrequency = 
        from word in s.Split(' ')
        group word by word
        into wordGrouping
        select new {wordGrouping.Key, Count = wordGrouping.Count()};

Upvotes: 0

CodingGorilla
CodingGorilla

Reputation: 19842

I'm not sure if it's more efficient or "resource light", but you can do:

string[] words = "peter piper picked a pack of pickled peppers, the peppers were sweet and sower for peter, peter thought".Split(" ");
int peter = words.Count(x=>x == "peter");
int peppers = words.Count(x=>x == "peppers");
// etc

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

This should do the trick:

var str = "peter piper picked a pack of pickled peppers, the peppers were sweet and sower for peter, peter thought";
var counts = str
    .Split(' ', ',')
    .GroupBy(s => s)
    .ToDictionary(g => g.Key, g => g.Count());

Now the dictionary counts contains word-count pairs from your sentence. For example, counts["peter"] is 3.

Upvotes: 4

Related Questions