我的目标是获取一个句子文件,应用一些基本过滤,然后将剩余的句子输出到一个文件和终端。我正在使用 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 左右的某个地方被截断。删除拼写检查完全消除了截断。