2012-03-09 77 views
5

我使用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(good)example”这个句子,它会报告“(很”和“很好”)拼写错误。或者如果字符串包含时间(如“8:30”),则会将其报告为拼写错误的单词。它也有逗号问题等。

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

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

回答

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 docs,支持\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 
} 

有关正则表达式的更多信息here。 我读完之后this我觉得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; 
    } 
} 

变种NumberOfMistakes = content.GetWords()其中(x => hunspell.Spell(X)!)计数()。;