gpt4 book ai didi

Python YACC EOF 立即到达

转载 作者:太空宇宙 更新时间:2023-11-03 13:41:34 25 4
gpt4 key购买 nike

晚上好

我正在学习使用 Ply(Python 3/Win 8.1 系统)在 lex/yacc 上工作,但我遇到了一个障碍:我似乎无法让 yacc 正确读取输入文件。

如果我对输入文件的内容进行硬编码,我会得到预期的结果,但如果我尝试从中读取,yacc 只是从状态 0 到达文件末尾,在句法分析真正开始之前就停止了。

这是我的主要内容( token 和句法规则在上面定义 - 它们似乎不是问题,因为当输入是硬编码时程序运行良好):

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

最佳答案

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

关于Python YACC EOF 立即到达,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30156365/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com