






















大文件单词统计
- 使用 StreamReader 分块读取,结合 Parallel.ForEach 并行统计,结果存入 ConcurrentDictionary<string,int>。
using System; using System.Collections.Concurrent; using System.IO; using System.Linq; using System.Text.RegularExpressions; class BigFileWordCounter { static void Main() { // 替换成你的大文件路径 string filePath = @"D:\large_file.txt"; // 线程安全字典:存储最终统计结果 var wordCount = new ConcurrentDictionary<string, int>(StringComparer.OrdinalIgnoreCase); Console.WriteLine("开始统计单词..."); var startTime = DateTime.Now; // 1. 流式读取文件(分块,不占内存) var lines = File.ReadLines(filePath); // 2. 并行处理每一行 Parallel.ForEach(lines, line => { if (string.IsNullOrWhiteSpace(line)) return; // 正则提取单词(忽略标点、数字,只保留字母) var words = Regex.Matches(line, @"[a-zA-Z]+") .Cast<Match>() .Select(m => m.Value.ToLower()); // 统一小写,避免大小写重复统计 // 3. 并行更新线程安全字典 foreach (var word in words) { wordCount.AddOrUpdate( key: word, addValue: 1, // 不存在则添加,值=1 updateValueFactory: (k, oldVal) => oldVal + 1 // 存在则+1 ); } }); var endTime = DateTime.Now; Console.WriteLine($"\n统计完成!耗时:{(endTime - startTime).TotalSeconds:F2} 秒"); Console.WriteLine($"不重复单词总数:{wordCount.Count}"); // 输出前20个高频词(可选) Console.WriteLine("\n【出现频率最高的前20个单词】"); foreach (var item in wordCount.OrderByDescending(kv => kv.Value).Take(20)) { Console.WriteLine($"{item.Key,-15} {item.Value,6} 次"); } } }
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。