跟进英语语法分析器

时间:2009-06-23 20:23:53

标签: c++

我最近问了一个关于编写一个非常基本的英语语法分析器的问题。我认为显示一些代码(虽然非常难看)可能有助于指定我在实现语法方面需要帮助的地方。这是代码。评论表明问题。

#include "std_lib_facilities.h"

string sentence();
string noun();
string verb();

string article()
{
string words = sentence(); // not sure how to check for words
           if (words == "the")
           words = sentence();
           else return words;        
}

string verb()
{
string words = sentence(); // not sure how to check for words
           if (words == "rules" || words == "fly" || words == "swim")
           words = sentence();
           else return words;                   
}

string noun()
{
string words = sentence(); // not sure how to check for words
           if (words == "birds" || words == "fish" || words == "C++")
           words = sentence();
           else return words;                   
}

string conjunction()
{
string words = sentence(); // not sure how to check for words
          if (words == "and" || words == "but" || words == "or")
          words = sentence();
          else return words;                  
}

string sentence()
{
if (noun()){ // this fails to compile, not sure how to check this 
             // error message says could not convert noun to bool  
    if (verb())
       cout << "OK.\n";
    else cout << "Not OK.\n";}
else if (article()){
                   if (sentence()) // will this create a loop?
                      cout << "Ok.\n";
                   else cout << "Not Ok.\n";}
else if (conjunction()){
    if (sentence()) // actually needs to be sentence conjunction sentence
       cout << "Ok.\n";
       else cout << "Not Ok.\n";
else cout << "Not OK.\n";

}


int main()
{                                   
string words;
cout << "Enter sentence.\n";
while(cin >> words){
      sentence();
      }
keep_window_open(); // this function is part of the facilities library
}

代码非常不完整,但基本上是需要发生的框架。主要的问题是我需要检查一个函数是否为真,我需要知道如何比较用户输入到被调用函数(除了strcasecmp()以外的任何东西?它还没有被用在书中,所以必须是另一种方式。)我也担心可能有多个输出“OK”或“Not OK”,但我稍后会担心。

4 个答案:

答案 0 :(得分:1)

了解lex&amp; yacc可以更轻松,更优雅地实现这一目标。

答案 1 :(得分:1)

解析自然语言是一项非常艰巨的任务。特别要从头开始做。

您可以考虑使用现有的库,例如Link Grammar Parser(C,与我相似的自定义GPL兼容免费软件许可证,对许多语言都有绑定)或RelEx(Java, Apache许可证)。

添加:找到一些AGFL grammar for English

答案 2 :(得分:0)

您可以做的一件事是让函数返回bool而不是字符串,并将对字符串的引用作为参数传递给函数调用。这至少可以让您检查函数的返回值。

答案 3 :(得分:0)

我已经使用NLTK

完成了这项工作

它非常强大,但使用Python而不是C ++。很多聊天机器人都使用此工具包进行编码,您也可以试用它们