2009-06-23 78 views
1

我最近問了一個關於編寫一個非常基本的英語語法分析器的問題。我認爲這可能有助於展示一些代碼(雖然非常難看),以指定我在實現語法時需要幫助的地方。這是代碼。評論表明問題。追溯到英語語法分析器

#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」或「不好」的輸出,但我會在後面擔心。

+0

編輯原始問題以包含此代碼可能會更好。 – CoderDennis 2009-06-23 20:49:38

+0

我做了,沒有迴應。 – Alex 2009-06-23 21:59:12

回答

1

看看lex & yacc更簡單更優雅的方式來實現這一點。

0

你可以做的一件事就是讓函數返回布爾值而不是字符串,並將字符串引用作爲參數傳遞給函數調用。這至少可以讓你檢查函數的返回值。

1

解析自然語言是一項非常艱鉅的任務。特別是要完全從頭開始。您可以考慮使用現有的庫,如Link Grammar Parser(C,自定義GPL兼容免費軟件許可證,它似乎很像BSD,對許多語言有約束力)或RelEx(Java,Apache許可證)。

地址:找到一些AGFLgrammar for English

0

我已經與NLTK

這是非常強大,但使用Python,而不是C++做了。很多聊天機器人都使用此工具包進行編碼,您也可以試用它們