如何访问和写入从文件读取的字符串数组中的每个单词到 C# 中的新文件?
how to access and write each word in string array read from a file onto a new file in c#?
我的测试文件包含:
processes
deleting
agreed
这是 C# 中的代码
PorterStemmer testing = new PorterStemmer();
string temp,stemmed;
string[] lines = System.IO.File.ReadAllLines(@"C:\Users\PJM\Documents\project\testerfile.txt");
System.Console.WriteLine("Contents of testerfile.txt = ");
for (int i = 0; i <2; i++)
{
temp = lines[i];
stemmed = testing.StemWord(temp);
System.IO.File.WriteAllText(@"C:\Users\PJM\Documents\project\testerfile3.txt", stemmed);
Console.WriteLine("\t" + stemmed);
}
在 运行 代码之后,testerfile3 仅包含 "agre" 。
所以我的问题是我希望单独处理字符串数组中的每个单词,即我在访问字符串数组时遇到问题。有没有办法访问字符串数组中的每个索引?
来自 WriteAllText 的文档:
If the target file already exists, it is overwritten.
因此 for 循环中的每次迭代都会覆盖文件,而您只剩下上一次迭代的文本。
您可以使用 System.IO.File.AppendAllText
代替
此外,您可以使用数组的长度 属性 遍历所有单词 for (int i = 0; i < lines.Length; i++)
或者,您可以使用 LINQ 的 Select 将非词干线投影到词干线并使用 AppendAllLines
写入结果,而不是 for 循环:
System.IO.File.AppendAllLines(@"C:\Users\PJM\Documents\project\testerfile3.txt", lines.Select(l => testing.StemWord(l)));
我的测试文件包含:
processes
deleting
agreed
这是 C# 中的代码
PorterStemmer testing = new PorterStemmer();
string temp,stemmed;
string[] lines = System.IO.File.ReadAllLines(@"C:\Users\PJM\Documents\project\testerfile.txt");
System.Console.WriteLine("Contents of testerfile.txt = ");
for (int i = 0; i <2; i++)
{
temp = lines[i];
stemmed = testing.StemWord(temp);
System.IO.File.WriteAllText(@"C:\Users\PJM\Documents\project\testerfile3.txt", stemmed);
Console.WriteLine("\t" + stemmed);
}
在 运行 代码之后,testerfile3 仅包含 "agre" 。 所以我的问题是我希望单独处理字符串数组中的每个单词,即我在访问字符串数组时遇到问题。有没有办法访问字符串数组中的每个索引?
来自 WriteAllText 的文档:
If the target file already exists, it is overwritten.
因此 for 循环中的每次迭代都会覆盖文件,而您只剩下上一次迭代的文本。
您可以使用 System.IO.File.AppendAllText
代替
此外,您可以使用数组的长度 属性 遍历所有单词 for (int i = 0; i < lines.Length; i++)
或者,您可以使用 LINQ 的 Select 将非词干线投影到词干线并使用 AppendAllLines
写入结果,而不是 for 循环:
System.IO.File.AppendAllLines(@"C:\Users\PJM\Documents\project\testerfile3.txt", lines.Select(l => testing.StemWord(l)));