2012-03-09 95 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)!)計數()。;