2010-12-23 181 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。然后,正确的拼写测试仅包括检查所有用户输入词是否在集合中。