如何使用rply库解析多个表达式

1 投票
1 回答
1040 浏览
提问于 2025-04-18 13:13

我用Python的rply库创建了一个解析器,现在可以进行基本的算术运算。问题是,当我从文件中读取时,无法解析多于一行的内容。

比如我有一行:5 + 4。

这行可以正常解析,没有错误。但如果我有这样的内容,分成两行:

5 + 4

7 * 3

我就会遇到这个错误:rply.errors.ParsingError。

我已经设置我的词法分析器忽略换行和空格:

lg.ignore('\n')
lg.ignore('\s+')

这些是我的生成规则:

@pg.production('main : expression')
def main(p):
    return p[0]

@pg.production(’expression : NUMBER’)
def expression_number(p):
    return Number(int(p[0].getstr()))

@pg.production(’expression : expression PLUS expression’)
def expression_binop(p):
left = p[0]
right = p[2]
if p[1].gettokentype() == ’AND’:
    return Add(left, right)

如果能提供一些帮助,我会非常感激!谢谢!

相关问题:

1 个回答

1

这个方法是可行的,因为你没有设置乘法的部分:

from rply import ParserGenerator, LexerGenerator
from rply.token import BaseBox

lg = LexerGenerator()
# Add takes a rule name, and a regular expression that defines the rule.
lg.add("PLUS", r"\+")
lg.add("MINUS", r"-")
lg.add("NUMBER", r"\d+")
lg.add('MUL', r'\*') # added MUL here

lg.ignore(r"\s+")

# This is a list of the token names. precedence is an optional list of
# tuples which specifies order of operation for avoiding ambiguity.
# precedence must be one of "left", "right", "nonassoc".
# cache_id is an optional string which specifies an ID to use for
# caching. It should *always* be safe to use caching,
# RPly will automatically detect when your grammar is
# changed and refresh the cache for you.
pg = ParserGenerator(["NUMBER", "PLUS", "MINUS",'MUL'], # added MUL here
        precedence=[("left", ['PLUS', 'MINUS'])], cache_id="myparser")

@pg.production("main : expr")
def main(p):
    # p is a list, of each of the pieces on the right hand side of the
    # grammar rule
    return p[0]
@pg.production("expr : expr MUL expr") # added MUL here
@pg.production("expr : expr PLUS expr")
@pg.production("expr : expr MINUS expr")
def expr_op(p):
    lhs = p[0].getint()
    rhs = p[2].getint()
    if p[1].gettokentype() == "PLUS":
        return BoxInt(lhs + rhs)
    elif p[1].gettokentype() == "MINUS":
        return BoxInt(lhs - rhs)
    elif p[1].gettokentype() == 'MUL': # added Mul here
        return BoxInt(lhs * rhs)
    else:
        raise AssertionError("This is impossible, abort the time machine!")

@pg.production("expr : NUMBER")
def expr_num(p):
    return BoxInt(int(p[0].getstr()))

lexer = lg.build()
parser = pg.build()

class BoxInt(BaseBox):
    def __init__(self, value):
        self.value = value

    def getint(self):
        return self.value
with open("hello.txt") as f:
    for line in f:
        if line.strip():
            print parser.parse(lexer.lex(line)).value
21
9

撰写回答