获取文本中出现的单词数

时间:2012-01-26 21:54:39

标签: c# string linq

可以使用C#Linq完成吗?

例如:

  彼得·派珀挑了一包腌制的辣椒,辣椒是甜蜜的,撒种为彼得,彼得思想

结果:

peter 3
peppers 2
picked 1
...

我可以使用嵌套的for循环来实现它,但我认为使用Linq有一种更简洁,资源更轻的方式。

5 个答案:

答案 0 :(得分:6)

您可以使用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());

答案 1 :(得分:4)

这应该可以解决问题:

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());

现在字典counts包含您句子中的字数对。例如,counts["peter"]为3。

答案 2 :(得分:1)

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

是“彼得”,对其他人来说也是如此。

答案 3 :(得分:1)

我不确定它是否更有效或“资源轻”,但你可以这样做:

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

答案 4 :(得分:0)

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()};