6

我正在使用NHunspell来检查字符串中的拼写错误,如下所示:

var words = content.Split(' ');
string[] incorrect;
using (var spellChecker = new Hunspell(affixFile, dictionaryFile))
{
    incorrect = words.Where(x => !spellChecker.Spell(x))
        .ToArray();
}

这通常有效,但它有一些问题。例如,如果我检查句子“这是一个(非常好的)示例”,它会报告“(非常”和“好)”拼写错误。或者,如果字符串包含诸如“8:30”之类的时间,它会将其报告为拼写错误的单词。它也有逗号等问题。

Microsoft Word 足够智能,可以识别时间、分数或逗号分隔的单词列表。它知道何时不使用英语词典,也知道何时忽略符号。如何在我的软件中获得类似的、更智能的拼写检查?有没有提供更多智能的库?

编辑:我不想强迫用户在他们的机器上安装 Microsoft Word,所以使用 COM 互操作不是一个选项。

4

3 回答 3

6

如果您的拼写检查器真的那么愚蠢,您应该预先标记它的输入以取出单词并一次输入这些单词(或作为与空格连接的字符串)。我不熟悉 C#/.NET,但在 Python 中,你会使用一个简单的 RE \w+

>>> s = "This is a (very good) example"
>>> re.findall(r"\w+", s)
['This', 'is', 'a', 'very', 'good', 'example']

我敢打赌.NET 有一些非常相似的东西。事实上,根据.NET 文档\w支持,所以你只需要找出re.findall那里是如何调用的。

于 2012-03-09T18:00:22.687 回答
0
using System.Text.RegularExpressions;
...
// any occurence of ( and ) (maybe needs escaping)
string pattern = "( (\\.? | )\\.? )"; 
foreach(string i in incorrect){
  Regex.Replace(i, pattern, String.Empty) // replace with String.Empty
}

有关正则表达式的更多信息在这里。在我读完这篇文章之后,我认为 Hunspell 是最好的选择之一 :)

于 2012-03-09T18:15:15.453 回答
0

在 C# 中,你可以做这样的事情。

public static class ExtensionHelper
{
    public static string[] GetWords(this string input)
    {
        MatchCollection matches = Regex.Matches(input, @"\b[\w']*\b");

        var words = from m in matches.Cast<Match>()
                    where !string.IsNullOrEmpty(m.Value)
                    select TrimSuffix(m.Value);

        return words.ToArray();
    }

    public static string TrimSuffix(this string word)
    {
        int apostropheLocation = word.IndexOf('\'');
        if (apostropheLocation != -1)
        {
            word = word.Substring(0, apostropheLocation);
        }

        return word;
    }
}

var NumberOfMistakes = content.GetWords().Where(x => !hunspell.Spell(x)).Count();

于 2016-04-19T10:42:12.763 回答