这是一个包含几个文本文件的目录。如何计算每个文件中每个单词的频率?单词表示可以包含字母,数字和下划线字符的一组字符。
答案 0 :(得分:9)
这是一个应该计算文件中所有单词频率的解决方案:
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建议的结构。
答案 1 :(得分:3)
有一种Linq-ish替代品,imo更简单。这里的关键是使用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());
}
答案 2 :(得分: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>();
答案 3 :(得分:0)
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]++;
}
}
答案 4 :(得分: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);
}