请帮我写一个统计文法非终结符和终结符次数的c语言代码
时间: 2023-05-21 10:06:25 浏览: 120
以下是一个实现该功能的简单C++代码:
```
#include <iostream>
#include <fstream>
#include <map>
using namespace std;
int main() {
// 打开文件并读取内容
ifstream file("grammar.txt");
string content = "";
string line;
while (getline(file, line)) {
content += line;
}
file.close();
// 统计非终结符和终结符出现的次数
map<string, int> nonTerminals;
map<string, int> terminals;
int i = 0;
while (i < content.length()) {
if (content[i] == '<') {
// 统计非终结符
int j = i + 1;
while (j < content.length() && content[j] != '>') {
j++;
}
if (j < content.length()) {
string nonTerminal = content.substr(i, j - i + 1);
if (nonTerminals.find(nonTerminal) == nonTerminals.end()) {
nonTerminals[nonTerminal] = 1;
} else {
nonTerminals[nonTerminal]++;
}
i = j + 1;
}
} else if (isalpha(content[i])) {
// 统计终结符
int j = i;
while (j < content.length() && isalpha(content[j])) {
j++;
}
string terminal = content.substr(i, j - i);
if (terminals.find(terminal) == terminals.end()) {
terminals[terminal] = 1;
} else {
terminals[terminal]++;
}
i = j;
} else {
i++;
}
}
// 输出结果
cout << "Non-terminals: " << endl;
for (auto it = nonTerminals.begin(); it != nonTerminals.end(); it++) {
cout << it->first << " : " << it->second << endl;
}
cout << endl;
cout << "Terminals: " << endl;
for (auto it = terminals.begin(); it != terminals.end(); it++) {
cout << it->first << " : " << it->second << endl;
}
return 0;
}
```
该代码假定输入的语法文件是一个.txt文件,将文件中的内容读入字符串后进行解析,统计非终结符和终结符出现的次数,并输出结果。
阅读全文