2010-12-23 118 views
2

我正在尋找一種簡單的方法來檢查某個字符串是否拼寫正確的英文單詞。例如,'看'會返回True,'hurrr'會返回False。我不需要拼寫建議或任何拼寫糾正功能。只是一個簡單的函數,它接受一個字符串並返回一個布爾值。C++:檢查一個單詞是否拼寫正確

我可以用Python使用PyEnchant輕鬆實現這一點,但似乎你必須自己編譯庫,如果你想使用MS Visual C++。

+0

相關:http://stackoverflow.com/questions/862699/c-spellchecker-library – nico 2010-12-23 18:37:21

回答

3

PyEnchant基於Enchant,它是一個提供C和C++接口的C庫。所以你可以將它用於C++。最小例子是這樣的:

#include <memory> 
#include <cstdio> 

#include "enchant.h" 
#include "enchant++.h" 

int main() 
{ 
    try 
     { 
      enchant::Broker *broker = enchant::Broker::instance(); 
     std::auto_ptr<enchant::Dict> dict (broker->request_dict ("en_US")); 

      const char *check_checks[] = { "hello", "helllo" }; 
      for (int i = 0; i < (sizeof (check_checks)/sizeof (check_checks[0])); ++i) 
     { 
      printf ("enchant_dict_check (%s): %d\n", check_checks[i], 
       dict->check (check_checks[i]) == false); 
     } 

    } catch (const enchant::Exception &) { 
     return 1; 
    } 
} 

更多的例子/測試,看看他們SVN repository

2

如果你想自己實現這樣的功能,你需要一個數據庫來查詢給定的單詞是否有效(通常是純文本文件就足夠了,例如Linux上的/usr/share/dict/words)。

否則,您可以依靠第三方拼寫檢查庫來做到這一點。

-1
bool spell_check(std::string const& str) 
{ 
    std::cout << "Is '" << str << "' spelled correctly? "; 
    std::string input; 
    std::getline(input); 

    return input[0] == 'y' || input[0] == 'Y'; 
} 
+2

這到底是什麼? – 2010-12-23 18:41:16

+0

一個蹩腳的,但正確的給定的規格,對問題的迴應。 – 2010-12-23 18:42:14

2

你可以採取的GNU字典一個在那裏(就像提到/usr/share/dict/words),並將其打造成爲一個合適的數據結構,它會給你根據快速查找和成員檢查您的性能需求,就像一個directed acyclic word graph或甚至只是trie可能就足夠了。

1

對於初學者,您需要一個單詞列表。 (/usr/share/dict/words也許?)

您應該將您的單詞列表讀入std::set。然後,正確的拼寫測試僅包括檢查所有用戶輸入詞是否在集合中。