我最近問了一個關於編寫一個非常基本的英語語法分析器的問題。我認爲這可能有助於展示一些代碼(雖然非常難看),以指定我在實現語法時需要幫助的地方。這是代碼。評論表明問題。追溯到英語語法分析器
#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」或「不好」的輸出,但我會在後面擔心。
編輯原始問題以包含此代碼可能會更好。 – CoderDennis 2009-06-23 20:49:38
我做了,沒有迴應。 – Alex 2009-06-23 21:59:12