繁体   English   中英

写入文件中断

[英]Write to file cut off

我的目标是获取一个句子文件,应用一些基本过滤,并将剩余的句子输出到文件和终端。 我正在使用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;
    }

这是写入文件的代码:

        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);
            }

这是检查器:

    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;
    }

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

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

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

w.Flush();
w.Close();

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

using( var w = new StreamWriter(...) )
{
  // Do stuff
  w.Flush();
}

你完成写作后是否关闭了StreamWriter 你可以尝试这样的事情:

using(StreamWriter w = new StreamWriter(outFile))
{
    foreach(string x in xs)
    {
        if(Checker.check(x, speller))
        {
            w.WriteLine("[{0}]", x);
            Console.WriteLine("[{0}]", x);
        }
    }
}

using的语句将关闭StreamWriter (通过调用Dispose的方法StreamWriter )中的代码执行完毕后。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM