晚上好,
我正在学习使用Ply (Python3/ Win 8.1系统)在lex/yacc上工作,但我遇到了一个麻烦:我似乎无法让yacc正确地读取输入文件。
如果我硬编码输入文件的内容,我就会得到预期的结果,但是如果我尝试从它读取,yacc就会从状态0到达文件的末尾,在它真正开始之前停止语法分析。
以下是我的主要内容(上面定义了标记和语法规则--它们似乎并不是问题所在,因为当输入是硬编码时,程序运行良好):
if __name__ == "__main__":
import sys
lexer = lex.lex()
yacc.yacc()
inputfile = open(sys.argv[1], 'r', encoding="UTF-8")
lexer.input(inputfile.read())
for token in lexer: #for this part, the file is read correctly
print("line %d : %s (%s) " % (token.lineno, token.type, token.value))
result = yacc.parse(inputfile.read(), debug=True)
print(result) #Stack immediately contains . $end and the p_error(p) I've defined confirms EOF was reached
tmp = "{{var1 := 'some text' ; var2 := 'some other text' ; var3 := ( 'text', 'text2') ; }}" #Same contents as the input file
result = yacc.parse(tmp, debug=True)
print(result) #correct results发布于 2015-05-10 20:40:01
inputfile.read()读取到文件的末尾,所以在它成功完成之后,您知道文件位于EOF。
您应该只读取()文件的内容一次:
if __name__ == "__main__":
import sys
lexer = lex.lex()
yacc.yacc()
with open(sys.argv[1], 'r', encoding="UTF-8") as inputfile:
contents = inputfile.read()
lexer.input(contents)
for token in lexer: #for this part, the file is read correctly
print("line %d : %s (%s) " % (token.lineno, token.type, token.value))
result = yacc.parse(contents, debug=True)
print(result) #Stack immediatly contains . $end and the p_error(p) I've defined confirms EOF was reached
tmp = "{{var1 := 'some text' ; var2 := 'some other text' ; var3 := ( 'text', 'text2') ; }}" #Same contents as the input file
result = yacc.parse(tmp, debug=True)
print(result) #correct results发布于 2015-05-10 20:53:58
使用"with as“也可能是一个好主意,它更容易阅读(imo),并且更‘健壮’:
with open(sys.argv[1], 'r', encoding="UTF-8") as inputfile:
lexer.input(inputfile.read())https://stackoverflow.com/questions/30156365
复制相似问题