文件读入LR(1)分析表代码
时间: 2023-11-30 17:03:44 浏览: 32
下面是使用Python语言实现文件读入LR(1)分析表的示例代码:
```python
# 读取LR(1)分析表文件
with open('lr1_table.txt', 'r') as f:
# 读取终结符和非终结符列表
terminals = f.readline().strip().split()
non_terminals = f.readline().strip().split()
# 构建ACTION表和GOTO表
action_table = {}
goto_table = {}
for line in f:
state, action, target = line.strip().split()
if action in terminals:
action_table[(state, action)] = target
else:
goto_table[(state, action)] = target
# 打印ACTION表和GOTO表
print('ACTION表:')
for state in action_table:
print(state[0], state[1], action_table[state])
print('GOTO表:')
for state in goto_table:
print(state[0], state[1], goto_table[state])
```
在上述代码中,假设LR(1)分析表文件的格式如下:
```
a b c $ d e f
S A B C D E F
0 a 2
0 b 1
1 c 3
2 d s4
3 e r1
4 f acc
```
其中,第一行为终结符列表,第二行为非终结符列表,从第三行开始为ACTION表和GOTO表的内容,每行三个字段分别表示状态、动作和目标状态。代码首先打开文件并读取终结符和非终结符列表,然后依次读取每行内容,并根据动作是终结符还是非终结符将其添加到ACTION表或GOTO表中。最后打印ACTION表和GOTO表。