Python pyparsing 模块,infixNotation() 实例源码
我们从Python开源项目中,提取了以下3个代码示例,用于说明如何使用pyparsing.infixNotation()。
def expression_parser(self):
"""A function returning a (pyparsing) parser for parsing C expressions.
Returns:
a (pyparsing) parser for parsing C expressions.
"""
precedence = (self._build_precedence(_UNARY_MACROS) +
self._build_precedence(_PRECEDENCE))
self.expression = pyparsing.Forward()
# pylint: disable=expression-not-assigned
self.expression << (
pyparsing.infixNotation(
baseExpr=self._base_or_array_expression(),
opList=precedence,
)
)
return self.expression
def tag_delta(expression, tag_list):
"""Take in a tag expression and a list of tags and give the delta of tags to meet the expression
:return tuple( list( "required tags" ),list( "tuple of options" ) )
"""
if tag_list is None:
tag_list = []
required_tags = []
optional_tags = []
def parse_and(tokens):
args = tokens[0][0::2]
extend_list = filter(lambda x: isinstance(x, str) and x not in tag_list, args)
required_tags.extend(extend_list)
def parse_or(tokens):
args = tokens[0][0::2]
append_list = filter(lambda x: isinstance(x, args)
if append_list == args:
optional_tags.append(tuple(append_list))
identifier = pp.Word(pp.alphanums + "_" + "-" + "'")
expr = pp.infixNotation(identifier, [
("AND", 2, pp.opAssoc.LEFT, parse_and),
("OR", parse_or),
("and",
("or",
])
expr.parseString(expression)
if expression and not required_tags and expression not in tag_list:
# single tag in the expression
required_tags.append(expression)
return required_tags, optional_tags
def __init__(self):
"""
Create a parser that parse arithmetic expressions. They can
contains variable identifiers or raw numbers. The meaning
for the identifiers is left to the
"""
number = p.Regex(r'\d+(\.\d*)?([eE]\d+)?')
identifier = p.Word(p.alphas)
terminal = identifier | number
self._expr = p.infixNotation(terminal, [
(p.oneOf('* /'), p.opAssoc.LEFT),
(p.oneOf('+ -'), p.opAssoc.LEFT)
]) + p.stringEnd()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。