You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#中段落单词总数统计及重复单词出现次数计数方案求助

C# 段落单词频次统计实现方案

直接上两种实用的实现方式,同时解决文本预处理(大小写、标点干扰)的问题:

方法一:使用Dictionary手动统计(适合理解底层逻辑)

先对原始段落做清洗(统一大小写、去除标点),再拆分单词,最后遍历计数:

string paragraph = "Your input paragraph here. Hello world! Hello again, world.";

// 预处理:转小写,移除非字母数字的字符(可根据需求调整规则)
string cleanedParagraph = Regex.Replace(paragraph.ToLower(), @"[^a-z0-9\s]", "");

// 拆分单词(按空白字符分割,过滤空字符串)
string[] words = cleanedParagraph.Split(new[] { ' ', '\t', '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);

// 统计总单词数
int totalWords = words.Length;
Console.WriteLine($"总单词数:{totalWords}");

// 统计每个单词的出现次数
Dictionary<string, int> wordCounts = new Dictionary<string, int>();
foreach (string word in words)
{
    if (wordCounts.ContainsKey(word))
    {
        wordCounts[word]++;
    }
    else
    {
        wordCounts.Add(word, 1);
    }
}

// 输出结果
foreach (var pair in wordCounts)
{
    Console.WriteLine($"单词「{pair.Key}」出现 {pair.Value} 次");
}

方法二:使用LINQ GroupBy(简洁高效)

利用LINQ的分组功能,快速完成频次统计,同时兼顾预处理:

string paragraph = "Your input paragraph here. Hello world! Hello again, world.";

// 预处理+拆分+统计一步到位
var wordStats = paragraph
    .ToLower()
    .Split(new[] { ' ', '\t', '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries)
    .Select(word => Regex.Replace(word, @"[^a-z0-9]", "")) // 移除单词中的标点
    .Where(word => !string.IsNullOrEmpty(word)) // 过滤空字符串
    .GroupBy(word => word)
    .Select(g => new { Word = g.Key, Count = g.Count() });

// 总单词数
int totalWords = wordStats.Sum(s => s.Count);
Console.WriteLine($"总单词数:{totalWords}");

// 输出每个单词的频次
foreach (var stat in wordStats)
{
    Console.WriteLine($"单词「{stat.Word}」出现 {stat.Count} 次");
}

关键说明

  • 预处理步骤很重要:如果不统一大小写,"Hello"和"hello"会被算作不同单词;不移除标点,"world"和"world."也会被区分。
  • 拆分规则可调整:Split的分隔符可以根据需求添加(比如中文空格、制表符等),StringSplitOptions.RemoveEmptyEntries能避免空字符串干扰。
  • 如果需要保留大小写区分,去掉.ToLower()即可;如果要保留特定标点,修改正则表达式的过滤规则。

内容的提问来源于stack exchange,提问作者Muhammad Aqeel Khan Abbasi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 00:07:12