【发布时间】:2012-01-26 21:54:39
【问题描述】:
这可以使用 C# Linq 完成吗?
例如:
peter piper 摘了一包泡椒,对 peter 来说,辣椒又甜又甜,peter 想
结果:
peter 3
peppers 2
picked 1
...
我可以使用嵌套的 for 循环来做到这一点,但我认为使用 Linq 有一种更简洁、资源轻的方式。
【问题讨论】:
这可以使用 C# Linq 完成吗?
例如:
peter piper 摘了一包泡椒,对 peter 来说,辣椒又甜又甜,peter 想
结果:
peter 3
peppers 2
picked 1
...
我可以使用嵌套的 for 循环来做到这一点,但我认为使用 Linq 有一种更简洁、资源轻的方式。
【问题讨论】:
您可以使用 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());
【讨论】:
这应该可以解决问题:
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。
【讨论】:
Regex.Split(str, @"\W").GroupBy... 来简化分词。宫缩会很麻烦,所以可能是[.,;:!?""\s-] 之类的。
string.Empty 的计数,因为您在原始字符串中有“,”部分...
Split(...) 之后的零件。不过,感谢您提及空字符串!
我不确定它是否更有效或“资源光”,但你可以这样做:
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
【讨论】:
"peter piper picked a pack of pickled peppers,the peppers
were sweet and sower for peter, peter thought"
.Split(' ', ',').Count(x=>x == "peter");
the 代表“peter”,其他人也一样。
【讨论】:
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()};
【讨论】: