3

私の目標は、文のファイルを取得し、いくつかの基本的なフィルタリングを適用して、残りの文をファイルとターミナルに出力することです。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 前後のさまざまな長さで切断されます。スペルチェックを削除すると、切断が完全になくなります。

4

2 に答える 2

7

ストリームを閉じる前に、ストリームをフラッシュする必要があります。

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

ステートメント (これusingも使用する必要があります) は、ストリームを自動的に閉じますが、フラッシュしません。

using( var w = new StreamWriter(...) )
{
  // Do stuff
  w.Flush();
}
于 2011-04-12T19:59:31.043 に答える
2

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ます。DisposeStreamWriter

于 2011-04-12T19:58:43.643 に答える