有一个包含一些文本文件的目录。如何计算每个文件中每个单词的频率?单词是指一组字符,可以包含字母、数字和下划线字符。
user266003
问问题
16317 次
5 回答
10
这是一个应该计算文件中所有单词频率的解决方案:
private void countWordsInFile(string file, Dictionary<string, int> words)
{
var content = File.ReadAllText(file);
var wordPattern = new Regex(@"\w+");
foreach (Match match in wordPattern.Matches(content))
{
int currentCount=0;
words.TryGetValue(match.Value, out currentCount);
currentCount++;
words[match.Value] = currentCount;
}
}
您可以像这样调用此代码:
var words = new Dictionary<string, int>(StringComparer.CurrentCultureIgnoreCase);
countWordsInFile("file1.txt", words);
在此之后单词将包含文件中的所有单词及其频率(例如words["test"]
返回“test”在文件内容中的次数。如果您需要从多个文件累积结果,只需调用所有文件的方法使用相同的字典。如果您需要为每个文件提供单独的结果,则每次创建一个新字典并使用@DarkGray 建议的结构。
于 2012-03-31T11:43:34.350 回答
3
有一个 imo 更简单的 Linq-ish 替代方案。这里的关键是使用内置的框架File.ReadLines
(懒人阅读很酷)和string.Split
.
private Dictionary<string, int> GetWordFrequency(string file)
{
return File.ReadLines(file)
.SelectMany(x => x.Split())
.Where(x => x != string.Empty)
.GroupBy(x => x)
.ToDictionary(x => x.Key, x => x.Count());
}
要从许多文件中获取频率,您可以基于params
.
private Dictionary<string, int> GetWordFrequency(params string[] files)
{
return files.SelectMany(x => File.ReadLines(x))
.SelectMany(x => x.Split())
.Where(x => x != string.Empty)
.GroupBy(x => x)
.ToDictionary(x => x.Key, x => x.Count());
}
于 2013-12-09T16:15:51.527 回答
0
字数计算:
int WordCount(string text)
{
var regex = new System.Text.RegularExpressions.Regex(@"\w+");
var matches = regex.Matches(text);
return matches.Count;
}
从文件中读取文本:
string text = File.ReadAllText(filename);
字数统计结构:
class FileWordInfo
{
public Dictionary<string, int> WordCounts = new Dictionary<string, int>();
}
List<FileWordInfo> fileInfos = new List<FileWordInfo>();
于 2012-03-29T20:52:21.823 回答
0
@aKzenT 答案很好,但有问题!他的代码从不检查字典中是否已经存在该单词!所以我修改了代码如下:
private void countWordsInFile(string file, Dictionary<string, int> words)
{
var content = File.ReadAllText(file);
var wordPattern = new Regex(@"\w+");
foreach (Match match in wordPattern.Matches(content))
{
if (!words.ContainsKey(match.Value))
words.Add(match.Value, 1);
else
words[match.Value]++;
}
}
于 2013-12-09T14:57:22.647 回答
0
string input= File.ReadAllText(filename);
var arr = input.Split(' ');
// finding frequencies of words in a string
IDictionary<string, int> dict = new Dictionary<string, int>();
foreach (var item in arr)
{
var count = 0;
if (dict.TryGetValue(item, out count))
dict[item] = ++a;
else
dict.Add(item, 1);
}
于 2019-05-27T20:43:53.993 回答