我正在开发一个小程序,用于删除给定语法中的单位生产。我开发了一个对我来说正确的逻辑。我面临的问题是我无法访问Python中存储在列表中的字符串的下一个立即索引。
gram=[line.rstrip('\n') for line in open("grammar.txt","r+")]
non_terminals=[]
productions=[]
for item in range(len(gram)):
non_terminals.append(gram[item][0])
print(non_terminals)
temp=[]
for item in range(len(gram)):
for str in non_terminals:
if gram[item][0] is str:
productions.append(gram[item].lstrip(str).lstrip('-'+'>'))
temp=''
for item in range(len(productions)):
for str in range(len(productions[item])):
for nt in non_terminals:
if productions[item][str] is nt:
if productions[item][str-1] is '|' and (productions[item] [str+1] is '|'):
i=nt.index(nt)
temp=productions[item].rstrip(nt)
temp=temp+productions[i]
print(productions)
print(temp)
我收到错误
如果productions [item] [str-1]是'|'和(productions [item] [str + 1]是'|'): IndexError:字符串索引超出范围
文本文件包含
S->S+T|T
T->T*F|F
F->(S)|a
任何人都可以建议我出于什么原因无法这样做。?