[英]reading/writing to txt file in C#
初学者在这里 ,
我很难理解如何在c#中编辑txt文件的内容。 我正在尝试执行以下-pseudocode:
foreach word in file.txt
if ((word.length < 4) || (word.length > 11))
delete word from file.txt
我需要做什么? 我知道它涉及流阅读器/编写器类,但我不知道它们如何工作。
乍看之下,使用StreamReader读取文件,在空间上分割然后删除不符合长度标准的单词,似乎很容易做到。 然后使用StreamWriter将结果写回。 但是,使用字符串解析(单词解析)时,您会遇到一堆“特殊”情况,可能需要额外的处理。
用编程语言很难描述单词。 例如,一个单词可能包含作为该单词一部分的标点符号,也可能以\\开头表示句子结尾,新行等的标点符号。
话虽如此,可以说我们有以下规则。
遵循这些规则,我们可以轻松阅读所有文本并执行您要求的操作。 我将从字处理开始。 您可以为此创建一个静态类。 让我们将此类称为WordProcessor
。
这是根据我们的规则从字符串解析单词的注释代码。
/// <summary>
/// characters that denote a new word
/// </summary>
const string wordSplitPuncuation = ",.!&()[] \"";
/// <summary>
/// Parse a string
/// </summary>
/// <param name="inputString">the string to parse</param>
/// <param name="preservePuncuation">preserve punctuation in the string</param>
/// <returns></returns>
public static IList<string> ParseString(string inputString, bool preservePuncuation)
{
//create a list to hold our words
List<string> rebuildWords = new List<string>();
//the current word
string currentWord = "";
//iterate through all characters in a word
foreach(var character in inputString)
{
//is the character is part of the split characters
if(wordSplitPuncuation.IndexOf(character) > -1)
{
if (currentWord != "")
rebuildWords.Add(currentWord);
if (preservePuncuation)
rebuildWords.Add("" + character);
currentWord = "";
}
//else add the word to the current word
else
currentWord += character;
}
return rebuildWords;
}
现在,上面的代码非常基础,如果将保留标点设置为true,则返回相同的字符串。
该类的下一部分实际上将用于删除小于特定长度或大于特定长度的单词。 这使用上面的方法将单词分成多个部分,并根据变量分别评估每个部分。
/// <summary>
/// Removes words from a string that are greater or less than the supplied lengths
/// </summary>
/// <param name="inputString">the input string to parse</param>
/// <param name="preservePuncuation">flag to preserve the puncation for rebuilding the string</param>
/// <param name="minWordLength">the minimum word length</param>
/// <param name="maxWordLength">the maximum word length</param>
/// <returns></returns>
public static string RemoveWords(string inputString, bool preservePuncuation, int minWordLength, int maxWordLength)
{
//parse our string into pieces for iteration
var words = WordProcessor.ParseString(inputString, preservePuncuation);
//initialize our complete string container
List<string> completeString = new List<string>();
//enumerate each word
foreach (var word in words)
{
//does the word index of zero matches our word split (as puncuation is one character)
if (wordSplitPuncuation.IndexOf(word[0]) > -1)
{
//are we preserviing puncuation
if (preservePuncuation)
//add the puncuation
completeString.Add(word);
}
//check that the word length is greater or equal to the min length and less than or equal to the max word length
else if (word.Length >= minWordLength && word.Length <= maxWordLength)
//add to the complete string list
completeString.Add(word);
}
//return the completed string by joining the completed string contain together, removing all double spaces and triming the leading and ending white spaces
return string.Join("", completeString).Replace(" ", " ").Trim();
}
好的,以上方法很简单地贯穿并提取了符合特定条件的单词,并保留了标点符号。 最后一个难题是读取\\将文件写入磁盘。 为此,我们可以使用StreamReader和StreamWriter 。 (请注意,如果您遇到文件访问问题,则可能需要查看FileStream类)。
现在,简单下面的相同代码读取文件,调用上面的方法,然后将文件写回到原始位置。
/// <summary>
/// Removes words from a file
/// </summary>
/// <param name="filePath">the file path to parse</param>
/// <param name="preservePuncuation">flag to preserve the puncation for rebuilding the string</param>
/// <param name="minWordLength">the minimum word length</param>
/// <param name="maxWordLength">the maximum word length</param>
public static void RemoveWordsFromAFile(string filePath, bool preservePuncuation, int minWordLength, int maxWordLength)
{
//our parsed string
string parseString = "";
//read the file
using (var reader = new StreamReader(filePath))
{
parseString = reader.ReadToEnd();
}
//open a new writer
using (var writer = new StreamWriter(filePath))
{
//parse our string to remove words
parseString = WordProcessor.RemoveWords(parseString, preservePuncuation, minWordLength, maxWordLength);
//write our string
writer.Write(parseString);
writer.Flush();
}
}
现在,上面的代码同样简单地打开了文件,根据您的参数解析了文件,然后重新编写了文件。
然后,可以通过简单地直接调用诸如之类的方法来重用它。
WordProcessor.RemoveWordsFromAFile(@"D:\test.txt", true, 4, 10);
最后一点。 这绝不是处理您的请求的最有效方法,也不是为提高性能而构建的。 这仅仅是关于如何从文件中解析单词的演示。
干杯
这个概念将遵循以下原则:
While(there is input to read from the input file)
{
read the input
if(input fits your criteria of shorter than 4 or longer than 11)
ignore it
else
write it to output file (which is a new file, NOT the file you read it from)
}
我将根据您在问题中描述的需求研究regex进行模式匹配:这是一个有关regex的很好的教程。 定位单词并用空格替换它们。
将其与以下有关如何读取/写入文本文件的文章结合在一起。 根据文件的大小,可以读取整个文件,删除要删除的单词,然后再将整个内容写回即可。 如何在C#中读取和写入文件
如果文件很大,则可能必须对此进行优化,然后分块读取文件。
尝试这个。
用空格作为分隔符分割文本以获取数组中的单词。
然后加入该数组中的单词以满足您的条件
到文本文件。
var filePath = HttpRuntime.AppDomainAppPath + "your file path";
if (!File.Exists(filePath))
return;
using (var sr = new StreamReader(filePath))
{
var text = sr.ReadToEnd();
if (text.Length < 4 || text.Length > 11)
{
using (var sw = new StreamWriter(filePath))
{
sw.Write("");
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.