本文整理汇总了Python中pyparsing.infixNotation函数的典型用法代码示例。如果您正苦于以下问题:Python infixNotation函数的具体用法?Python infixNotation怎么用?Python infixNotation使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了infixNotation函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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)
开发者ID:qlb7707,项目名称:webrtc_src,代码行数:34,代码来源:boolparse_lib.py
示例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]
开发者ID:pmacosta,项目名称:peng,代码行数:28,代码来源:functions.py
示例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
开发者ID:ledgr,项目名称:postomaat,代码行数:29,代码来源:complexrules.py
示例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
开发者ID:atwong589,项目名称:rekall,代码行数:28,代码来源:expression_parser.py
示例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()
开发者ID:eanikolaev,项目名称:ir,代码行数:11,代码来源:search.py
示例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
开发者ID:fabrice102,项目名称:private_multiplication,代码行数:11,代码来源:lib_desc.py
示例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()
开发者ID:bigluster,项目名称:monasca-analytics,代码行数:13,代码来源:expression.py
示例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
开发者ID:santtu,项目名称:freezr,代码行数:49,代码来源:filter.py
示例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
开发者ID:adam-urbanczyk,项目名称:cadquery,代码行数:42,代码来源:selectors.py
示例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
开发者ID:almatr,项目名称:rekall,代码行数:20,代码来源:expression_parser.py
示例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]
开发者ID:drossegger,项目名称:lmc,代码行数:21,代码来源:ltlparser.py
示例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
开发者ID:johnfkraus,项目名称:pyparseurl,代码行数:36,代码来源:invRegex.py
示例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 = """
开发者ID:chahatupreti,项目名称:proper-codes,代码行数:30,代码来源:parsing+rules.py
示例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)
开发者ID:klahnakoski,项目名称:pyLibrary,代码行数:31,代码来源:sql_parser.py
示例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
开发者ID:nil0x42,项目名称:phpsploit,代码行数:31,代码来源:lucene_grammar.py
示例16: str
return "~" + str(self.arg)
__repr__ = __str__
__nonzero__ = __bool__
T = Keyword("True") | Keyword("true") | Keyword("T") | Keyword("1")
F = Keyword("False") | Keyword("false")| Keyword("F")| Keyword("0")
operand = T | F | Word(alphas, max=1)
operand.setParseAction(Operand)
# define expression, based on expression operand and
# list of operations in precedence order
expression = infixNotation( operand,
[
("not", 1, opAssoc.RIGHT, Not),
("and", 2, opAssoc.LEFT, And),
("or", 2, opAssoc.LEFT, Or),
])
def test():
symbols['p'] = True
symbols['q'] = False
symbols['r'] = True
tests = [("p", True),
("q", False),
("p and q", False),
("p and not q", True),
("not not p", True),
("not(p and q)", True),
("q or not p and r", False),
开发者ID:hobson,项目名称:ggpy,代码行数:32,代码来源:logic_pyparsing.py
示例17: Word
integer = Word(nums)
real = Combine(Word(nums) + "." + Word(nums))
variable = Word(alphas,exact=1)
operand = real | integer | variable
signop = oneOf('+ -')
multop = oneOf('* /')
plusop = oneOf('+ -')
expop = Literal('**')
# use parse actions to attach EvalXXX constructors to sub-expressions
operand.setParseAction(EvalConstant)
arith_expr = infixNotation(operand,
[
(signop, 1, opAssoc.RIGHT, EvalSignOp),
(expop, 2, opAssoc.LEFT, EvalPowerOp),
(multop, 2, opAssoc.LEFT, EvalMultOp),
(plusop, 2, opAssoc.LEFT, EvalAddOp),
])
comparisonop = oneOf("< <= > >= != = <> LT GT LE GE EQ NE")
comp_expr = infixNotation(arith_expr,
[
(comparisonop, 2, opAssoc.LEFT, EvalComparisonOp),
])
def main():
# sample expressions posted on comp.lang.python, asking for advice
# in safely evaluating them
rules=[
'( A - B ) = 0',
开发者ID:johnfkraus,项目名称:pyparseurl,代码行数:31,代码来源:eval_arith.py
示例18: Group
mongo_op.setParseAction(
lambda t: t[0].replace('>=', '$gte').replace('>', '$gt').replace('<=', '$lte').replace('<', '$lt')
)
one_sided_range = Group(mongo_op('op') + valid_word('bound'))('onesidedrange')
term = (_range | one_sided_range | regex | wildcard | phrase | single_term)
clause << (Optional(field_name + COLON, default='__default_field__')('field') +
(term('term') | Group(LPAR + query_expr + RPAR)('subquery')))
clause.addParseAction(SearchTerm)
query_expr << infixNotation(clause,
[
(required_modifier | prohibit_modifier, 1, opAssoc.RIGHT, SearchModifier),
((not_ | '!').setParseAction(lambda: 'NOT'), 1, opAssoc.RIGHT, SearchNot),
((and_ | '&&').setParseAction(lambda: 'AND'), 2, opAssoc.LEFT, SearchAnd),
(Optional(or_ | '||').setParseAction(lambda: 'OR'), 2, opAssoc.LEFT, SearchOr),
])
class QueryParser:
DEFAULT_FIELD = 'text'
DEFAULT_OPERATOR = '$regex'
def parse(self, query, default_field=None, default_operator=None):
self.default_field = default_field or QueryParser.DEFAULT_FIELD
self.default_operator = default_operator or QueryParser.DEFAULT_OPERATOR
return repr(query_expr.parseString(query)[0])\
开发者ID:guardian,项目名称:alerta,代码行数:31,代码来源:queryparser.py
示例19: __str__
return not v
def __str__(self):
return "~" + str(self.arg)
__repr__ = __str__
__nonzero__ = __bool__
TRUE = Keyword("True")
FALSE = Keyword("False")
boolOperand = TRUE | FALSE | Word(alphas,max=1)
boolOperand.setParseAction(BoolOperand)
# define expression, based on expression operand and
# list of operations in precedence order
boolExpr = infixNotation( boolOperand,
[
("not", 1, opAssoc.RIGHT, BoolNot),
("and", 2, opAssoc.LEFT, BoolAnd),
("or", 2, opAssoc.LEFT, BoolOr),
])
if __name__ == "__main__":
p = True
q = False
r = True
tests = [("p", True),
("q", False),
("p and q", False),
("p and not q", True),
("not not p", True),
("not(p and q)", True),
("q or not p and r", False),
开发者ID:vmuriart,项目名称:pyparsing,代码行数:32,代码来源:simpleBool.py
示例20: Group
COMMA + Group(expr)("if_false") + RPAR)
statFunc = lambda name : Group(CaselessKeyword(name) + Group(LPAR + delimitedList(expr) + RPAR))
sumFunc = statFunc("sum")
minFunc = statFunc("min")
maxFunc = statFunc("max")
aveFunc = statFunc("ave")
funcCall = ifFunc | sumFunc | minFunc | maxFunc | aveFunc
multOp = oneOf("* /")
addOp = oneOf("+ -")
numericLiteral = pyparsing_common.number
operand = numericLiteral | funcCall | cellRange | cellRef
arithExpr = infixNotation(operand,
[
(multOp, 2, opAssoc.LEFT),
(addOp, 2, opAssoc.LEFT),
])
textOperand = dblQuotedString | cellRef
textExpr = infixNotation(textOperand,
[
('&', 2, opAssoc.LEFT),
])
expr << (arithExpr | textExpr)
(EQ + expr).runTests("""\
=3*A7+5
=3*Sheet1!$A$7+5
开发者ID:svn2github,项目名称:pyparsing,代码行数:31,代码来源:excelExpr.py
注:本文中的pyparsing.infixNotation函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论