【发布时间】:2015-05-01 12:12:40
【问题描述】:
问题:我需要遍历文件夹中的多个文件并阅读它们。它们是 .txt 文件。阅读时我需要注意每个文件中出现的单词。
例如:
文件 1 文本:“约翰是我的朋友朋友”-> 词:约翰,是,我的,朋友
文件 2 文本:“John is Mark” -> 单词:John, is, Mark
目前我正在读取文件,然后将其制成一个大文件,但它不能像这样工作,所以我必须单独阅读它们。老想法:
string[] filesZ = { "1.txt", "2.txt" };
var allLinesZ = filesZ.SelectMany(i => System.IO.File.ReadAllLines(i));
System.IO.File.WriteAllLines("n.txt", allLinesZ.ToArray());
var logFileZ = File.ReadAllLines("n.txt");
所以这是第一个问题,如何在不制作大文件的情况下遍历它们并读取所有这些。
第二个是如何对单独文件的所有单词进行计数,目前我正在使用一个大文件:
var logFileZ = File.ReadAllLines("n.txt");
List<string> LogListZ = new List<string>(logFileZ);
var fi = new Dictionary<string, int>();
LogListZ.ForEach(str => AddToDictionary(fi, str));
foreach (var entry in fi)
{
Console.WriteLine(entry.Key + ": " + entry.Value);
}
这是 AddToDictionary:
static void AddToDictionary(Dictionary<string, int> dictionary, string input)
{
input.Split(new[] { ' ', ',', '.', '?', '!', '.' }, StringSplitOptions.RemoveEmptyEntries).ToList().ForEach(n =>
{
if (dictionary.ContainsKey(n))
dictionary[n]++;
else
dictionary.Add(n, 1);
});
}
我正在考虑对所有文件进行循环(可能吗?)并在里面创建一个计数器来计算单词,例如 John 在多少个文件中。我不需要一个特定的文件号,只需要一个单词的出现次数,而不需要计算(如示例文件 1 中的)单词两次(朋友)。
【问题讨论】:
标签: c# file stream iteration streamreader