写入文件中断

Isa*_* G. 3 c# file-io hunspell

我的目标是获取一个句子文件,应用一些基本过滤,并将剩余的句子输出到文件和终端.我正在使用Hunspell库.

这是我如何从文件中获取句子:

    public static string[] sentencesFromFile_old(string path)
    {
        string s = "";
        using (StreamReader rdr = File.OpenText(path))
        {
            s = rdr.ReadToEnd();
        }
        s = s.Replace(Environment.NewLine, " ");
        s = Regex.Replace(s, @"\s+", " ");
        s = Regex.Replace(s, @"\s*?(?:\(.*?\)|\[.*?\]|\{.*?\})", String.Empty);
        string[] sentences = Regex.Split(s, @"(?<=\. |[!?]+ )");
        return sentences;
    }
Run Code Online (Sandbox Code Playgroud)

这是写入文件的代码:

        List<string> sentences = new List<string>(Checker.sentencesFromFile_old(path));
        StreamWriter w = new StreamWriter(outFile);
        foreach(string x in xs)
            if(Checker.check(x, speller))
            {
                w.WriteLine("[{0}]", x);
                Console.WriteLine("[{0}]", x);
            }
Run Code Online (Sandbox Code Playgroud)

这是检查器:

    public static bool check(string s, NHunspell.Hunspell speller)
    {
        char[] punctuation = {',', ':', ';', ' ', '.'};
        bool upper = false;
        // Check the string length.
        if(s.Length <= 50 || s.Length > 250)
            return false;
        // Check if the string contains only allowed punctuation and letters.
        // Also disallow words with multiple consecutive caps.
        for(int i = 0; i < s.Length; ++i)
        {
            if(punctuation.Contains(s[i]))
                continue;
            if(Char.IsUpper(s[i]))
            {
                if(upper)
                    return false;
                upper = true;
            }
            else if(Char.IsLower(s[i]))
            {
                upper = false;
            }
            else return false;
        }
        // Spellcheck each word.
        string[] words = s.Split(' ');
        foreach(string word in words)
            if(!speller.Spell(word))
                return false;
        return true;
    }
Run Code Online (Sandbox Code Playgroud)

句子打印在终端上就好了,但文本文件以2015字符中断句子.那是怎么回事?

编辑:当我删除check方法的某些部分时,文件被切断为2000或4000左右的各种长度.删除拼写检查完全消除了截止.

Pau*_*der 6

您需要在关闭流之前刷新流.

w.Flush();
w.Close();
Run Code Online (Sandbox Code Playgroud)

using语句(您也应该使用)将自动关闭流,但不会刷新它.

using( var w = new StreamWriter(...) )
{
  // Do stuff
  w.Flush();
}
Run Code Online (Sandbox Code Playgroud)