琐碎的字符串解析算法
Trivial string parse algorithm
在这个代码示例中,我对向量使用const-ref,并检查四个函数中的条件。如果每个条件都有一个大列表(例如,数据库中的所有动词(例如,英语词典)),那么在传递给函数之前,最好在类Token中检查一下(这样函数只会得到值动词),还是在函数内检查一下(所以函数本身必须检查数据库)?
#include <iostream>
#include <string>
#include <vector>
using namespace std;
bool full_stop_check(vector<string> &sentence);
bool verb_check(vector<string> &sentence, int index);
bool noun_check(vector<string> &sentence, int index);
bool conj_arti_check(vector<string> &sentence, int index);
int main ()
{
vector<string> sentence;
string temp_word;
while(cin >> temp_word)
{
sentence.push_back(temp_word);
}
// Output test (commented out)
// for (string x : sentence)
// cout << x << 'n';
// Check for sentence
if (full_stop_check(sentence))
cout << "It is a sentence." << 'n';
else
cout << "It is not a sentence." << 'n';
return 0;
}
bool full_stop_check(vector<string> &sentence)
{
int index = sentence.size()-1;
// Full Stop Check
if (sentence[index] != ".")
return false;
--index;
if (index < 0 )
return false;
return verb_check(sentence, index); // full stop (not first character)
}
bool verb_check(vector<string> &sentence, int index)
{
// Verb Check
if (sentence[index] != "verb")
return false;
--index;
if (index < 0 )
return false;
return noun_check(sentence, index); // verb (not first word)
}
bool noun_check(vector<string> &sentence, int index)
{
// Noun Check
if (sentence[index] != "noun")
return false;
--index;
if (index < 0 ) // first word is a noun
return true;
return conj_arti_check(sentence, index); // noun (not first word)
}
bool conj_arti_check(vector<string> &sentence, int index)
{
// Conjugation & Article Check
if (sentence[index] != "conjugation" && sentence[index] != "article")
return false;
// If it is either an article or conjugation
if (index == 0 && sentence[index] == "article") // first word is an article
return true;
else if (index == 0) // first word not article (or noun)
return false;
else if (sentence[index] == "conjugation") { // conjugation
--index;
return verb_check(sentence, index);
}
else { // article (not first word)
--index;
return conj_arti_check(sentence, index); // recursion
}
}
上下文无关语言识别器之外的理论通常基于下推自动机(具有递归的状态机)。手工处理它非常乏味,但很容易自动化,因此存在相当多的解析器生成器,如yacc、ANTLR或BOOST Spirit。它们只是获取语言语法并生成相应的解析器代码。
相关文章:
- 高效的字符串截断算法,按顺序删除相等的前缀和后缀
- 如何使用 STL 算法将整数向量转换为字符串向量?
- 字符串::find在c++中使用了哪种算法
- 将来C++的标准库会包含网络、字符串算法,..吗?
- 如何将字符串保存在最长的常见子序列递归算法中
- 使用图形的字符串搜索算法?C++
- 重新定义要在字符串的 STL 算法中使用的<运算符
- 字符串相似性算法返回错误值
- "map"容器C++是否对字符串的连续子字符串应用 Rabin-Karp 算法?
- 如何实现将前缀与字符串匹配的最快算法
- 如何在没有 c++ 中的数组/算法的情况下对两个条件的字符串进行排序
- 用户输入字符串的情节算法
- 在三元字符串中处理一元NOT运算符的调车场算法
- 罗马数字基本算法中基于字符串的错误(使用std::map)
- 如何使用STL算法找到字符串中分隔两个不同字母的最短星号序列
- 对于字符串/句子不起作用的最接近的匹配算法
- 是否有一种算法可以查找字符串中任何指定字符的第一次出现
- 在不使用默认算法的情况下对字符串的 std 向量进行排序
- 字符串算法分析的排列
- 您将如何改进此算法?(c字符串反转)