本文整理汇总了Python中pyparsing.infixNotation函数的典型用法代码示例。如果您正苦于以下问题:Python infixNotation函数的具体用法?Python infixNotation怎么用?Python infixNotation使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了infixNotation函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: BoolstrResult
def BoolstrResult(expr, true_variables):
"""Determine if a boolean expression is satisfied.
BoolstrResult('A and B and not C', {'A', 'C'}) -> False
Args:
expr: The orginal boolean expression, like 'A and B'.
true_variables: Collection to be checked whether satisfy the boolean expr.
Returns:
True if the given |true_variables| cause the boolean expression |expr| to
be satisfied, False otherwise.
"""
boolstr = _ExprOverwrite(expr, true_variables)
# Define the boolean logic
TRUE = pyparsing.Keyword('True')
FALSE = pyparsing.Keyword('False')
boolOperand = TRUE | FALSE
boolOperand.setParseAction(_BoolOperand)
# Define expression, based on expression operand and list of operations in
# precedence order.
boolExpr = pyparsing.infixNotation(
boolOperand, [('not', 1, pyparsing.opAssoc.RIGHT, _BoolNot),
('and', 2, pyparsing.opAssoc.LEFT, _BoolAnd),
('or', 2, pyparsing.opAssoc.LEFT, _BoolOr),])
try:
res = boolExpr.parseString(boolstr)[0]
return bool(res)
except (AttributeError, pyparsing.ParseException):
raise BoolParseError('Cannot parse the boolean expression string "%s".'
% expr)
示例2: _parse_expr
def _parse_expr(text, ldelim="(", rdelim=")"):
"""Parse mathematical expression using PyParsing."""
var = pyparsing.Word(pyparsing.alphas + "_", pyparsing.alphanums + "_")
point = pyparsing.Literal(".")
exp = pyparsing.CaselessLiteral("E")
number = pyparsing.Combine(
pyparsing.Word("+-" + pyparsing.nums, pyparsing.nums)
+ pyparsing.Optional(point + pyparsing.Optional(pyparsing.Word(pyparsing.nums)))
+ pyparsing.Optional(
exp + pyparsing.Word("+-" + pyparsing.nums, pyparsing.nums)
)
)
atom = var | number
oplist = [
(pyparsing.Literal("**"), 2, pyparsing.opAssoc.RIGHT),
(pyparsing.oneOf("+ - ~"), 1, pyparsing.opAssoc.RIGHT),
(pyparsing.oneOf("* / // %"), 2, pyparsing.opAssoc.LEFT),
(pyparsing.oneOf("+ -"), 2, pyparsing.opAssoc.LEFT),
(pyparsing.oneOf("<< >>"), 2, pyparsing.opAssoc.LEFT),
(pyparsing.Literal("&"), 2, pyparsing.opAssoc.LEFT),
(pyparsing.Literal("^"), 2, pyparsing.opAssoc.LEFT),
(pyparsing.Literal("|"), 2, pyparsing.opAssoc.LEFT),
]
# Get functions
expr = pyparsing.infixNotation(
atom, oplist, lpar=pyparsing.Suppress(ldelim), rpar=pyparsing.Suppress(rdelim)
)
return expr.parseString(text)[0]
示例3: makeparser
def makeparser(values):
SimpleExpression = PF_KEYWORD('pfvalue') + AttOperator('operator') + AttOperand('testvalue')
booleanrule = infixNotation( SimpleExpression,
[
("!", 1, opAssoc.RIGHT, BoolNot),
("&&", 2, opAssoc.LEFT, BoolAnd),
("||", 2, opAssoc.LEFT, BoolOr),
])
def evalResult(loc,pos,tokens):
modifiers=None
l=len(tokens)
if l==3:
pfixname,op,checkval=tokens
elif l==4:
pfixname,op,checkval,modifiers=tokens
else:
pfixname = op = checkval = None
logging.error("Parser error, got unexpected token amount, tokens=%s"%tokens)
#print "checking %s %s %s"%(pfixname,op,checkval)
return ValueChecker(values,pfixname,op,checkval,modifiers)
SimpleExpression.setParseAction(evalResult)
#SimpleExpression.setDebug()
configline=booleanrule + ACTION + restOfLine
return configline
示例4: expression_parser
def expression_parser():
"""A function returning a (pyparsing) parser for parsing C expressions.
Returns:
a (pyparsing) parser for parsing C expressions.
"""
precedence = []
for operators, arity, associativity in _PRECEDENCE:
if arity <= 2:
operators = pyparsing.Or(map(pyparsing.Literal, operators))
else:
operators = tuple(map(pyparsing.Literal, operators))
precedence.append((
operators,
arity,
associativity,
_construct_operator(arity),
))
expression = pyparsing.Forward()
# pylint: disable=expression-not-assigned
expression << pyparsing.infixNotation(
baseExpr=_base_or_array_expression(expression),
opList=precedence,
lpar=pyparsing.NoMatch(),
rpar=pyparsing.NoMatch(),
)
expression.ignore(pyparsing.cppStyleComment)
return expression
示例5: eval_query
def eval_query(query_str):
global WORD_CHARS
boolOperand = Word(WORD_CHARS)
boolOperand.setParseAction(BoolOperand)
boolExpr = infixNotation(
boolOperand,
[("not", 1, opAssoc.RIGHT, BoolNot), ("and", 2, opAssoc.LEFT, BoolAnd), ("or", 2, opAssoc.LEFT, BoolOr)],
)
return boolExpr.parseString(query_str.lower())[0].calcop()
示例6: get_term_bnf
def get_term_bnf():
global term_bnf
if not term_bnf:
val = Word(alphanums).setParseAction(DescValNode.get_parse_action())
term_bnf = infixNotation(
val,
[
(None, 2, opAssoc.LEFT, DescXorNode.get_parse_action())
]
)
return term_bnf
示例7: __init__
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('* /'), 2, p.opAssoc.LEFT),
(p.oneOf('+ -'), 2, p.opAssoc.LEFT)
]) + p.stringEnd()
示例8: get_parser
def get_parser():
op_literal = ((Word(alphanums + ",.-_")
| dblQuotedString.setParseAction(removeQuotes)
| sglQuotedString.addParseAction(removeQuotes)).
addParseAction(toks0(Literal)))
op_tag = (Keyword('tag')
+ Suppress('[')
+ op_literal
+ Suppress(']')).setParseAction(Tag)
op_value = (op_tag
| (oneOf(" ".join(Variable.VARIABLES))
.setParseAction(toks0(Variable))))
op_lhs = op_value
op_rhs = op_value | op_literal
op_compare = (Keyword("=") | Keyword("~") | Keyword("!=") | Keyword("!~"))
op_and = Keyword("and")
op_or = Keyword("or")
op_not = Keyword("not")
op_true = Suppress(Keyword("true")).setParseAction(toksz(AlwaysTrue))
op_false = Suppress(Keyword("false")).setParseAction(toksz(AlwaysFalse))
op_compare_expression = ((op_lhs
+ op_compare
+ op_rhs)
.addParseAction(toks(Comparison)))
op_test_expression = (Group(op_lhs)
.addParseAction(lambda s, l, t: t[0])
.addParseAction(NotNull))
op_value_expression = (op_false
| op_true
| op_compare_expression
| op_test_expression)
op_expression = (
StringStart()
+ infixNotation(
op_value_expression,
[(Suppress(op_not), 1, opAssoc.RIGHT, toks00(Not)),
(Suppress(op_and), 2, opAssoc.LEFT, toks0(And)),
(Suppress(op_or), 2, opAssoc.LEFT, toks0(Or))])
+ StringEnd())
return op_expression
示例9: _makeExpressionGrammar
def _makeExpressionGrammar(atom):
"""
Define the complex string selector grammar using PyParsing (which supports
logical operations and nesting)
"""
#define operators
and_op = Literal('and')
or_op = Literal('or')
delta_op = oneOf(['exc','except'])
not_op = Literal('not')
def atom_callback(res):
return _SimpleStringSyntaxSelector(res)
atom.setParseAction(atom_callback) #construct a simple selector from every matched
#define callback functions for all operations
def and_callback(res):
items = res.asList()[0][::2] #take every secend items, i.e. all operands
return reduce(AndSelector,items)
def or_callback(res):
items = res.asList()[0][::2] #take every secend items, i.e. all operands
return reduce(SumSelector,items)
def exc_callback(res):
items = res.asList()[0][::2] #take every secend items, i.e. all operands
return reduce(SubtractSelector,items)
def not_callback(res):
right = res.asList()[0][1] #take second item, i.e. the operand
return InverseSelector(right)
#construct the final grammar and set all the callbacks
expr = infixNotation(atom,
[(and_op,2,opAssoc.LEFT,and_callback),
(or_op,2,opAssoc.LEFT,or_callback),
(delta_op,2,opAssoc.LEFT,exc_callback),
(not_op,1,opAssoc.RIGHT,not_callback)])
return expr
示例10: expression_parser
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
示例11: parseLTL
def parseLTL(s):
TRUE = Keyword("True")
FALSE = Keyword("False")
symbol = TRUE | FALSE | Word("abcdefghijklmnopqrstuvwxyz")
equation = symbol + "==" + symbol | symbol + "<" + symbol | symbol
symbol.setParseAction(Const)
expr= infixNotation(symbol,
[
(negop, 1, opAssoc.RIGHT, Negltl),
(fop, 1, opAssoc.RIGHT, Fltl),
(gop, 1, opAssoc.RIGHT, Gltl),
(xop, 1, opAssoc.RIGHT, Xltl),
(andop, 2, opAssoc.RIGHT, Andltl),
(orop, 2, opAssoc.RIGHT, Orltl),
(impop, 2, opAssoc.RIGHT, Impltl),
(uop, 2, opAssoc.RIGHT, Ultl),
(vop, 2, opAssoc.RIGHT, Vltl)
])
return expr.parseString(s)[0]
示例12: parser
def parser():
global _parser
if _parser is None:
ParserElement.setDefaultWhitespaceChars("")
lbrack,rbrack,lbrace,rbrace,lparen,rparen,colon,qmark = map(Literal,"[]{}():?")
reMacro = Combine("\\" + oneOf(list("dws")))
escapedChar = ~reMacro + Combine("\\" + oneOf(list(printables)))
reLiteralChar = "".join(c for c in printables if c not in r"\[]{}().*?+|") + " \t"
reRange = Combine(lbrack + SkipTo(rbrack,ignore=escapedChar) + rbrack)
reLiteral = ( escapedChar | oneOf(list(reLiteralChar)) )
reNonCaptureGroup = Suppress("?:")
reDot = Literal(".")
repetition = (
( lbrace + Word(nums).setResultsName("count") + rbrace ) |
( lbrace + Word(nums).setResultsName("minCount")+","+ Word(nums).setResultsName("maxCount") + rbrace ) |
oneOf(list("*+?"))
)
reRange.setParseAction(handleRange)
reLiteral.setParseAction(handleLiteral)
reMacro.setParseAction(handleMacro)
reDot.setParseAction(handleDot)
reTerm = ( reLiteral | reRange | reMacro | reDot | reNonCaptureGroup)
reExpr = infixNotation( reTerm,
[
(repetition, 1, opAssoc.LEFT, handleRepetition),
(None, 2, opAssoc.LEFT, handleSequence),
(Suppress('|'), 2, opAssoc.LEFT, handleAlternative),
]
)
_parser = reExpr
return _parser
示例13: Group
upto_N_words = Group(lpar + 'upto' + pyparsing_common.integer('numberofwords') + 'words' + rpar)
upto_N_chars = Group(lpar + 'upto' + pyparsing_common.integer('numberofchars') + 'characters' + rpar)
phrase_term = Group(OneOrMore(phrase_word) + ZeroOrMore(((upto_N_words) | ZeroOrMore(upto_N_chars)) + OneOrMore(phrase_word))) | quotedString # changed phrase_word to OneOrMore(phrase_word) to allow multi-word phrases
# phrase-term
# want to know if there is a way to just say that the phrase_term can contain both types of elements instead of
# having to give the exact grammar for it as p_w+upto+p_W
phrase_expr = infixNotation(phrase_term,
[
((BEFORE | AFTER | JOIN), 2, opAssoc.LEFT,), # (opExpr, numTerms, rightLeftAssoc, parseAction)
(NOT, 1, opAssoc.RIGHT,),
(AND, 2, opAssoc.LEFT,),
(OR, 2, opAssoc.LEFT),
],
lpar=Suppress('{'), rpar=Suppress('}')
) # structure of a single phrase with its operators
line_term = Group((LINE_CONTAINS | LINE_STARTSWITH | LINE_ENDSWITH)("line_directive") +
Group(phrase_expr)("phrase")) # basically giving structure to a single sub-rule having line-term and phrase
line_contents_expr = infixNotation(line_term,
[(NOT, 1, opAssoc.RIGHT,),
(AND, 2, opAssoc.LEFT,),
(OR, 2, opAssoc.LEFT),
]
) # grammar for the entire rule/sentence
sample1 = """
示例14: Literal
Literal("(").setName("func_param").setDebugActions(*debug) +
Optional(selectStmt | Group(delimitedList(expr)))("params") +
")"
).addParseAction(to_json_call).setDebugActions(*debug) |
ident.copy().setName("variable").setDebugActions(*debug)
)
expr << Group(infixNotation(
compound,
[
(
o,
3 if isinstance(o, tuple) else 2,
opAssoc.LEFT,
to_json_operator
)
for o in KNOWN_OPS
]+[
(
COLLATENOCASE,
1,
opAssoc.LEFT,
to_json_operator
)
]
).setName("expression").setDebugActions(*debug))
# SQL STATEMENT
selectColumn = Group(
Group(expr).setName("expression1")("value").setDebugActions(*debug) + Optional(Optional(AS) + ident.copy().setName("column_name1")("name").setDebugActions(*debug)) |
Literal('*')("value").setDebugActions(*debug)
).setName("column").addParseAction(to_select_call)
示例15: number
boost = CARAT + number("boost")
string_expr = Group(string + proximity_modifier) | string
word_expr = Group(valid_word + fuzzy_modifier) | valid_word
term << (
Optional(field_name("field") + COLON)
+ (word_expr | string_expr | range_search | Group(LPAR + expression + RPAR))
+ Optional(boost)
)
term.setParseAction(lambda t: [t] if "field" in t or "boost" in t else None)
expression << infixNotation(
term,
[
(required_modifier | prohibit_modifier, 1, opAssoc.RIGHT),
((not_ | "!").setParseAction(lambda: "NOT"), 1, opAssoc.RIGHT),
((and_ | "&&").setParseAction(lambda: "AND"), 2, opAssoc.LEFT),
(Optional(or_ | "||").setParseAction(lambda: "OR"), 2, opAssoc.LEFT),
],
)
# test strings taken from grammar description doc, and TestQueryParser.java
tests = r"""
a and b
a and not b
a and !b
a && !b
a&&!b
name:a
name:a and not title:b
(a^100 c d f) and !z