阅读文字段落。文件,拆分成句子,并打印到新文本。 c#中的文件

问题描述 投票:-1回答:2

我正在尝试编写c#代码,其中我应该读取txt中的段落。文件,然后拆分所有句子。然后,我应该将所有句子打印成一个新的txt。文件,他们仍然必须有他们所有的时期,并且必须完全一致。例如,如果段落是:这是第一句话。这是第二句话。这是第三句。然后输出(在一个新的txt。文件中)应该是:

这是第一句话。

这是第二句话。

这是第三句话。

我写了一些代码,这一切似乎都在起作用,除了最后有一个空行我不认为应该在那里,因为我检查了空行。这是我的代码:

  using System;
  using static System.Console;
  using System.IO;

 class Test
{
    public static void Main()
    {

        // Open the text file using a stream reader.
        using (StreamReader sr = new StreamReader("a.txt"))
        {

            // Read the stream to a string, and write the string to the console.
        String line = sr.ReadToEnd();

        string[] sentences = line.Split('.');

        using (StreamWriter newFile = new StreamWriter("b.txt"))

            for (int i = 0; i < sentences.Length; i++)
            {
                if (sentences[i].Length != 0)
                {
                    string outString = sentences[i].Trim() + ".";
                    newFile.WriteLine(outString);
                    WriteLine(outString);


                }
            }

        }

    }
}

我在这里得到的输出是:

这是第一句话。

这是第二句话。

这是第三句话。

[空行]

我不知道为什么我的txt末尾有空格。文件。任何帮助将不胜感激!!!

非常感谢。

c# split readfile
2个回答
2
投票

您是否尝试调试此以查看string[] sentences包含的内容?每个句子都有一个句点,然后你在它上面拆分,这样就会给你一个4行的数组:

1这是第一句2这是第二句3这是第三句4

然后你在每个结尾添加一个句号,这就是为什么你得到那个额外的句号。

您可以尝试添加string.IsNullOrEmpty检查每个句子以及.Trim()来清理空白区域。

foreach (string sentence in sentences)
{
   if (!string.IsNullOrEmpty(sentence))
       Console.WriteLine(sentence.Trim() + ".");
}

0
投票

据我所知,你想知道:

  1. 为什么句子之间有空格
  2. 为什么最后有两个点

当您使用方法时,Split(string str)空格包含在拆分中。如果你看一下你的例子,句子之间实际上有一些空格,所以它不会删除它们。

关于问题#2,你在每个句子都加一个点,因为Split方法消除了它们。示例文件末尾必须有一个空格,如下所示:And this is the third sentence.[space here]。 Split会在数组中放入第三个句子和点后面的空格。当然newFile.WriteLine(sentence + ".");在每个句子的末尾添加一个点,所以它占用了隐藏空间并在其末尾添加了一个点。您可以使用yourString.Trim()方法删除字符串之前和之后的每个空格。

© www.soinside.com 2019 - 2024. All rights reserved.