使用PLY解析Python

-2 投票
1 回答
779 浏览
提问于 2025-04-16 11:27

我正在尝试写一个Python解析器,我认为它应该能解析“if语句”,但实际上并不能。它给我显示了一个“语法错误”的提示。

有人能告诉我我哪里做错了吗?

提前谢谢大家。

代码在这里:https://github.com/narke/py2neko


我把输入字符串修改成了这样:

s = '''if 5:
    print 10
else:
    print 20 \n'''
check_syntax(s)

输出是:

Syntax error at '5'
atom: 10
factor None
None
cmp: None None
atom: 20
factor None
None
cmp: None None 
simple_stmt: None

1 个回答

1

根据你的代码:

s = "if 5:\n"
check_syntax(s)

if 5:\n 这个写法是不对的,因为它不是一个完整的 if 语句。你需要提供一段代码(也就是要执行的内容),当这个条件为 True 时才会执行。比如:

>>> if 5:
... 
  File "<stdin>", line 2

    ^
IndentationError: expected an indented block

>>> compile('if 5:\n', '<string>', 'exec')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1
    if 5:
        ^
SyntaxError: unexpected EOF while parsing

>>> compile('if 5:\n  print 5', '<string>', 'exec')
<code object <module> at 0xb7f60530, file "<string>", line 2>

撰写回答