【发布时间】:2010-12-27 14:53:16
【问题描述】:
我正在编写一个程序来计算文本文件中的单词数,该文本文件已经是小写并用空格分隔。我想使用字典,并且只计算字典中的单词。问题是字典非常大(约 100,000 个单词),每个文本文档也有约 50,000 个单词。因此,我在下面编写的代码变得非常慢(在 quad i7 机器上处理一个文档大约需要 15 秒)。我想知道我的编码是否有问题,是否可以提高程序的效率。非常感谢你的帮助。代码如下:
public static string WordCount(string countInput)
{
string[] keywords = ReadDic(); /* read dictionary txt file*/
/*then reads the main text file*/
Dictionary<string, int> dict = ReadFile(countInput).Split(' ')
.Select(c => c)
.Where(c => keywords.Contains(c))
.GroupBy(c => c)
.Select(g => new { word = g.Key, count = g.Count() })
.OrderBy(g => g.word)
.ToDictionary(d => d.word, d => d.count);
int s = dict.Sum(e => e.Value);
string k = s.ToString();
return k;
}
【问题讨论】:
-
你为什么要制作字典?