代码之家  ›  专栏  ›  技术社区  ›  Daniel

读取C中的.txt文件时出现问题#从(立即清空整行之后)到(下一个空整行之后)

  •  -1
  • Daniel  · 技术社区  · 7 年前

    我试图随机读取一个巨大的.txt文件。它有大量的段落,每个段落前后都有一行空白。我希望每次我随机阅读,它拉一个完整完整的段落,没有任何字符或单词的缺失,因为上下文。我提前感谢你的帮助。

    public static string GetRandomLine(string filename)
    {        
        var lines = File.ReadAllLines(filename);
        var lineNumber = _rand.Next(0, lines.Length);
        string reply = lines[lineNumber];
    
    
        return reply ;
    }
    
    0 回复  |  直到 7 年前
        1
  •  0
  •   TheCoderCrab    7 年前

    尝试以下操作:

            public static string[] GetRandomParagraph(string filePath)
            {
                if (File.Exists(filePath))
                {
                    string text = File.ReadAllText(filePath);
                    string[] paragraphs = text.Split(new string[] { "\n\n" }, StringSplitOptions.None);
                    return paragraphs[new Random().Next(0, paragraphs.Length)].Split('\n');
    
                }
                else
                    throw new FileNotFoundException("The file was not found", filePath);
            }
    

    我真的希望这就是你想要的。

        2
  •  0
  •   Ronan Thibaudau    7 年前
    // This builds a list of Paragraph first
    public static List<string> GetParagraphs(string filename)
    {        
        var paragraphs = new List<string>();
        var lines = File.ReadAllLines(filename);
        bool newParagraph = true;
        string CurrentParagraph = string.Empty;
        // Build the list of paragraphs by adding to the currentParagraph until empty lines and then starting a new one
        foreach(var line in lines)
        {
            if(newParagraph)
            {
                CurrentParagraph = line;
                newParagraph = false;
            }
            else
            {
                if(string.IsNullOrWhiteSpace(line))// we're starting a new paragraph, add it to the list of paragraphs and reset current paragraph for next one
                {
                    paragraphs.Add(CurrentParagraph);
                    CurrentParagraph = string.Empty;
                    newParagraph = true;
                }
                else // we're still in the same paragraph, add the line to current paragraph
                {
                    newParagraph += (Environment.NewLine + line);
                }
            }
        }
        // Careful, if your file doesn't end with a newline the last paragraph won't count as one, in that case add it manually here.
    }
    
    public static Random rnd = new Random();
    
    // And this returns a random one
    public static string GetRandomParagraph(string fileName)
    {
         var allParagraphs = GetParagraphs(filename);
         allParagraphs[rnd.Next(0,allParagraphs.length-1)]; // pick one of the paragraphs at random, stop at length-1 as collection indexers are 0 based    
    }
    

        3
  •  0
  •   Stephen    7 年前

    试试这个:

    public static string GetRandomLine(string filename)
        {
            var lines = File.ReadAllLines(filename);
            var lineNumber = _rand.Next(0, lines.Length - 1);
            var blankBefore = lineNumber;
            var blankAfter = lineNumber + 1;
            string reply = "";
    
            while (lines[blankBefore].Length > 0)
            {
                blankBefore--;
            }
    
            while (lines[blankAfter].Length != 0)
            {
                blankAfter++;
            }
    
            for ( int i = blankBefore + 1; blankBefore < blankAfter; blankBefore++)
            {
                reply += lines[i];
            }
            return reply;
        }
    

    根据您的描述,我假设文件以一个空白行开头和结尾。通过将随机行的独占上限设置为比行长度小1,可以避免随机行成为文件的最后一行。如果随机行是一个空行,blankBefore将是该行的索引,否则,它将被回溯到它到达上一个空白行。blankAfter从随机行之后的下一行的索引开始,如果该行不是空的,blankAfter将增加,直到它成为下一个空行的索引。

    一旦你在目标段落之前和之后都有空白行的索引,只需在它们之间附加行来回答。

    如果文件的第一行和最后一行不为空,则需要验证blankBefore和blankAfter是否仍在数组的边界内。

        4
  •  0
  •   Daniel    7 年前

    我对上面由@TheCoderCrab提供的代码做了一些修改。我把这个方法变成了一个字符串方法,这样它就会返回一个字符串。我只是简单地添加了一个for循环,将段落数组的所有字符追加到一个新字符串上,这个字符串将返回main。非常感谢。

    public static string GetRandomParagraph(string filePath)
        {
            if (File.Exists(filePath))
            {
                string text = File.ReadAllText(filePath);
                string[] paragraphs = text.Split(new string[] { "\n\n" }, StringSplitOptions.None);
                string [] paragraph = paragraphs[new Random().Next(0, paragraphs.Length)].Split('\n');
    
                //Added a for loop to build the string out of all the characters in the 'paragraph' array index.
                string pReturn = "";
                for (int a = 0; a < paragraph.Length; a++)
                {
                    //Loop through and consecutively append each character of mapped array index to a return string 'pReturn'
                    pReturn = pReturn + paragraph[a].ToString();
                }
    
                return pReturn;
    
            }
            else
                throw new FileNotFoundException("The file was not found", filePath);
        }
    
        5
  •  0
  •   ArcX    7 年前

    得到完整的段落

    public static string GetRandomParagraph(string fileName)
    {
        /* 
           Rather than reading all the lines, read all the text
           this gives you the ability to split by paragraph
        */
        var allText = File.ReadAllText(fileName);
        // Use as separator for paragraphs
        var paragraphSeparator = $"{Environment.NewLine}{Environment.NewLine}";
        // Treat large white spaces after a new line as separate paragraphs 
        allText = Regex.Replace(allText, @"(\n\s{3,})", paragraphSeparator);
        // Split the text into paragraphs
        var paragraphs = allText.Split(paragraphSeparator);
        // Get a random index between 0 and the amount of paragraphs
        var randomParagraph = new Random().Next(0, paragraphs.Length);
    
        return paragraphs[randomParagraph];
    }
    
    推荐文章