智能拼写检查

6

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

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

这种方法通常可行,但存在一些问题。例如,如果我正在检查句子“This is a (very good) example”,它会报告“(very”和“good)”拼写错误。或者如果字符串包含时间,如“8:30”,它会将其报告为拼写错误的单词。它还会出现逗号等问题。
Microsoft Word聪明到足以识别时间、分数或逗号分隔的单词列表。它知道什么时候不使用英语字典,并且知道何时应忽略符号。如何在我的软件中获得类似的更智能的拼写检查?是否有任何库提供了更多的智能功能?
编辑: 我不想强迫用户在他们的机器上安装Microsoft Word,因此使用COM interop不是一个选项。
3个回答

6

如果你的拼写检查器真的如此愚蠢,你应该对其输入进行预分词,从中获取单词并逐个或作为连接空格的字符串传递给它。我不熟悉C#/.NET,但在Python中,你可以使用一个简单的正则表达式\w+来实现:

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

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


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是最好的选择之一 :)


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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接