Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 获取文本中出现的单词数_C#_String_Linq - Fatal编程技术网

C# 获取文本中出现的单词数

C# 获取文本中出现的单词数,c#,string,linq,C#,String,Linq,这可以用C Linq实现吗 例如: 彼得·派珀挑选了一包腌制的辣椒,这些辣椒很甜,是彼得的播种者,彼得想 结果: peter 3 peppers 2 picked 1 ... 我可以用嵌套的for循环来实现它,但我认为使用Linq有一种更简洁、资源更少的方法 "peter piper picked a pack of pickled peppers,the peppers were sweet and sower for peter, peter thought" .Split(' ', '

这可以用C Linq实现吗

例如:

彼得·派珀挑选了一包腌制的辣椒,这些辣椒很甜,是彼得的播种者,彼得想

结果:

peter 3
peppers 2
picked 1
...
我可以用嵌套的for循环来实现它,但我认为使用Linq有一种更简洁、资源更少的方法

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

这是给彼得的,其他人也一样。

这应该可以做到:

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

现在,字典计数包含句子中的单词计数对。例如,计数[peter]为3。

我不确定它是否更高效或资源更轻,但您可以:

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

您可以使用Regex.Splitstr、@\W.GroupBy。。。为了简化断字。收缩会很麻烦,所以可能是[,;:!?\s-]或其他什么。你会得到字符串的计数。空的,考虑到这一点,正如你所拥有的,原始字符串中的部分…@ReedCopsey因为OP说他可以在循环中完成它,我几乎可以肯定他正在寻找调用Split后的部分。。。。不过,感谢您提及空字符串!
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());