我有一个文本文件存储为字符串变量。对文本文件进行处理,使其只包含小写单词和空格。现在,假设我有一个静态字典,它只是一个特定单词的列表,我想从文本文件中计算字典中每个单词的出现频率。例如:
Text file:
i love love vb development although i m a total newbie
Dictionary:
love, development, fire, stone
我希望看到的输出如下所示,列出了字典中的单词及其计数。如果它使编码变得更简单,它也只能列出文本中出现的字典单词。
===========
WORD, COUNT
love, 2
development, 1
fire, 0
stone, 0
============
使用正则表达式(例如"\w+")我可以获得所有匹配的单词,但我不知道如何获得字典中也有的计数,所以我被卡住了。效率在这里至关重要,因为字典很大(大约100,000个单词),文本文件也不小(每个文件大约200KB)。
我很感谢你的帮助。
发布于 2010-12-23 17:08:45
var dict = new Dictionary<string, int>();
foreach (var word in file)
if (dict.ContainsKey(word))
dict[word]++;
else
dict[word] = 1;
发布于 2010-12-23 17:09:33
您可以通过对字符串中的单词进行分组并将其转换为字典来计算其数量:
Dictionary<string, int> count =
theString.Split(' ')
.GroupBy(s => s)
.ToDictionary(g => g.Key, g => g.Count());
现在,您只需检查字典中是否存在这些单词,如果存在,则显示计数。
发布于 2010-12-23 17:28:59
使用Groovy regex facilty,我会这样做:
def input="""
i love love vb development although i m a total newbie
"""
def dictionary=["love", "development", "fire", "stone"]
dictionary.each{
def pattern= ~/${it}/
match = input =~ pattern
println "${it}" + "-"+ match.count
}
https://stackoverflow.com/questions/4520876
复制相似问题