我正在编写一个程序来计算文本文件中的单词数,该单词已经是小写并用空格分隔.我想使用字典,只计算字典中的单词IF.问题是字典很大(~100万字),每个文本文件也有~5,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;
}
Run Code Online (Sandbox Code Playgroud) 我有一个文本文件存储为字符串变量.处理文本文件,使其仅包含小写单词和空格.现在,假设我有一个静态字典,它只是一个特定单词列表,我想从文本文件中计算字典中每个单词的频率.例如:
Text file:
i love love vb development although i m a total newbie
Dictionary:
love, development, fire, stone
Run Code Online (Sandbox Code Playgroud)
我想看到的输出类似于以下内容,列出字典单词及其计数.如果它使编码更简单,它也只能列出文本中出现的字典单词.
===========
WORD, COUNT
love, 2
development, 1
fire, 0
stone, 0
============
Run Code Online (Sandbox Code Playgroud)
使用正则表达式(例如"\ w +")我可以获得所有单词匹配,但我不知道如何获得也在字典中的计数,所以我被卡住了.效率在这里至关重要,因为字典非常大(~100,000个单词),文本文件也不小(每个~200kb).
我感谢任何帮助.