Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/314.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在使用rply库时解析多个表达式_Python_Parsing - Fatal编程技术网

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

Python 如何在使用rply库时解析多个表达式,python,parsing,Python,Parsing,我使用python的rply库创建了一个解析器,目前可以执行基本的算法。问题是,在读取文件时,我不能解析多行。 假设我有: 5+4在一条线上 解析时没有错误。但是如果我有下面两行的内容 5+4 7*3 我得到这个错误:rply.errors.parsingeror 我已将lexer设置为忽略换行符和空格: lg.ignore('\n') lg.ignore('\s+') 这些是我的作品: @pg.production('main : expression') def main(p):

我使用python的rply库创建了一个解析器,目前可以执行基本的算法。问题是,在读取文件时,我不能解析多行。 假设我有: 5+4在一条线上

解析时没有错误。但是如果我有下面两行的内容

5+4

7*3

我得到这个错误:rply.errors.parsingeror

我已将lexer设置为忽略换行符和空格:

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)

任何帮助都将不胜感激!谢谢

这将起作用,您没有乘法设置:

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

你确定这是你的实际代码吗?您不应该在源代码中使用
'smart quotes'
。我从pdf中复制并粘贴了与实际代码匹配的代码。您有什么问题吗?我无法解析同一文件中的多个表达式。您尝试过剥离行吗?乘法只是一个示例。即使我从一个文件中解析两个连续的加法语句,它也不起作用。问题是解析一个文件中的多个语句,而不是每次只解析一个语句。它非常适合我从文件中读取。我将在回到计算机后添加如何使用它