• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python pyparsing.operatorPrecedence函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中pyparsing.operatorPrecedence函数的典型用法代码示例。如果您正苦于以下问题:Python operatorPrecedence函数的具体用法?Python operatorPrecedence怎么用?Python operatorPrecedence使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了operatorPrecedence函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: _getPattern

    def _getPattern(self):
        arith_expr = Forward()
        comp_expr = Forward()
        logic_expr = Forward()
        LPAR, RPAR, SEMI = map(Suppress, "();")
        identifier = Word(alphas+"_", alphanums+"_")
        multop = oneOf('* /')
        plusop = oneOf('+ -')
        expop = Literal( "^" )
        compop = oneOf('> < >= <= != ==')
        andop = Literal("AND")
        orop = Literal("OR")
        current_value = Literal( "." )
        assign = Literal( "=" )
        # notop = Literal('NOT')
        function = oneOf(' '.join(self.FUNCTIONS))
        function_call = Group(function.setResultsName('fn') + LPAR + Optional(delimitedList(arith_expr)) + RPAR)
        aggregate_column = QuotedString(quoteChar='{', endQuoteChar='}')
        single_column = QuotedString(quoteChar='[', endQuoteChar=']')
        integer = Regex(r"-?\d+")
        real = Regex(r"-?\d+\.\d*")

        # quotedString enables strings without quotes to pass

        operand = \
            function_call.setParseAction(self.__evalFunction) | \
            aggregate_column.setParseAction(self.__evalAggregateColumn) | \
            single_column.setParseAction(self.__evalSingleColumn) | \
            ((real | integer).setParseAction(self.__evalConstant)) | \
            quotedString.setParseAction(self.__evalString).addParseAction(removeQuotes) | \
            current_value.setParseAction(self.__evalCurrentValue) | \
            identifier.setParseAction(self.__evalString)

        arith_expr << operatorPrecedence(operand,
            [
             (expop, 2, opAssoc.LEFT, self.__expOp),
             (multop, 2, opAssoc.LEFT, self.__multOp),
             (plusop, 2, opAssoc.LEFT, self.__addOp),
            ])

        # comp_expr = Group(arith_expr + compop + arith_expr)
        comp_expr << operatorPrecedence(arith_expr,
            [
                (compop, 2, opAssoc.LEFT, self.__evalComparisonOp),
            ])

        logic_expr << operatorPrecedence(comp_expr,
            [
                (andop, 2, opAssoc.LEFT, self.__evalLogicOp),
                (orop, 2, opAssoc.LEFT, self.__evalLogicOp)
            ])

        pattern = logic_expr + StringEnd()
        return pattern
开发者ID:ArnoldOchieng,项目名称:echo-sense,代码行数:54,代码来源:expressionParser.py


示例2: __init__

    def __init__(self, EvaluateVariableChild=None, EvaluateNumberChild=None):
        EvaluateVariableChild = EvaluateVariableChild or EvaluateVariable
        EvaluateNumberChild = EvaluateNumberChild or EvaluateNumber
        # what is a float number
        floatNumber = Regex(r'[-]?\d+(\.\d*)?([eE][-+]?\d+)?')
        # a variable is a combination of letters, numbers, and underscor
        variable = Word(alphanums + "_")
        # a sign is plus or minus
        signOp = oneOf('+ -')
        # an operand is a variable or a floating point number
        operand = floatNumber ^ variable
        # when a floatNumber is found, parse it with evaluate number
        floatNumber.setParseAction(EvaluateNumberChild)
        # when a variable is found, parse it with the EvaluateVariableChild
        # or EvaluateVariable
        variable.setParseAction(EvaluateVariableChild)
        # comparisons include lt,le,gt,ge,eq,ne
        comparisonOp = oneOf("< <= > >= == !=")
        # negation of the boolean is !
        notOp = oneOf("!")
        # an expression is a either a comparison or
        # a NOT operation (where NOT a is essentially (a == False))
        comparisonExpression = operatorPrecedence(operand,
                                                  [
                                                   (comparisonOp,
                                                    2,
                                                    opAssoc.LEFT,
                                                    EvaluateComparison
                                                    ),
                                                   (notOp,
                                                    1,
                                                    opAssoc.RIGHT,
                                                    EvaluateNot
                                                    ),
                                                  ])

        # boolean logic of AND or OR
        boolOp = oneOf("& |")

        # a bool expression contains a nested bool expression or a comparison,
        # joined with a boolean operation
        boolExpression = Forward()
        boolPossible = boolExpression | comparisonExpression
        self.boolExpression = operatorPrecedence(boolPossible,
                                                 [
                                                  (boolOp,
                                                   2,
                                                   opAssoc.RIGHT,
                                                   EvaluateOrAnd
                                                   ),
                                                 ])
        return
开发者ID:eelsirhc,项目名称:boolparser,代码行数:52,代码来源:core.py


示例3: buildMapSyntax

 def buildMapSyntax(self):
     '''Subset of grammar for DMM files.
        
        "aai" = (/obj/structure/sign/securearea{desc = "A warning sign which reads 'HIGH VOLTAGE'"; icon_state = "shock"; name = "HIGH VOLTAGE"; pixel_y = -32},/turf/space,/area)
     '''
     dreamList = pyp.Forward()
     
     # Literals
     singlelineString = pyp.QuotedString('"', '\\').setResultsName('string').setParseAction(self.makeListString)
     fileRef = pyp.QuotedString("'", '\\').setResultsName('fileRef').setParseAction(self.makeFileRef)
     multilineString = pyp.QuotedString(quoteChar='{"', endQuoteChar='"}', multiline=True).setResultsName('string').setParseAction(self.makeListString)
     number = pyp.Regex(r'\-?\d+(\.\d*)?([eE]\d+)?').setResultsName('number').setParseAction(self.makeListNumber)
     
     #  Paths
     relpath = pyp.ident | relpath + SLASH + pyp.ident
     abspath = SLASH + relpath
     path = (abspath | relpath).setParseAction(self.handlePath)
     pathslash = path + SLASH
     
     # Other symbols
     listStart = pyp.Suppress('list(')
     openParen = pyp.Suppress("(")
     closeParen = pyp.Suppress(')')
     
     # Grammar
     listConstant = singlelineString | fileRef | multilineString | number | dreamList | abspath
     listElement = listConstant | (listConstant + '=' + listConstant)
     listElement = pyp.operatorPrecedence(listElement, [
                             ("=", 2, pyp.opAssoc.LEFT,),
                             ])
     listContents = pyp.delimitedList(listElement)
     dreamList << pyp.Group(listStart + listContents + closeParen)
     dreamList.setParseAction(self.makeList)
     
     
     # DMM Atom definition
     atomDefProperty = pyp.ident + "=" + listConstant 
     atomDefProperty = pyp.operatorPrecedence(atomDefProperty, [
                             ("=", 2, pyp.opAssoc.LEFT,),
                             ])
     atomDefPropertyListContents = pyp.delimitedList(listElement, delim=';')
     atomDefProperties = pyp.Suppress("{") + atomDefPropertyListContents + pyp.Suppress("}")
     atomDef = abspath | abspath + atomDefProperties
     
     # DMM Tile Definition
     tileDefListContents = pyp.delimitedList(atomDef)
     tileDefAtomList = openParen + tileDefListContents + closeParen
     tileDef = singlelineString + '=' + tileDefAtomList
     tileDef.setParseAction(self.makeTileDef)
     return tileDef
开发者ID:Boggart,项目名称:ByondTools,代码行数:50,代码来源:__init__.py


示例4: _algebra_to_ast

    def _algebra_to_ast(algebra_notation, inputs=None):
        """
            Converts a Boolean Algebra expression to an abstract syntax tree.
        """

        #convert each of the VHDL input terms into a grammar literal
        if inputs:
            inputTerms = reduce(lambda x, y : x | pyparsing.Literal(y.strip()), inputs)
        else:
            #create a basic identifier grammar element
            IdentifierChars = pyparsing.alphanums + '_[]'
            inputTerms = pyparsing.Word(IdentifierChars)

        #define the algebra operators, in order of precedence
        algebraOperators = \
            [
                ("'", 1, pyparsing.opAssoc.LEFT), #NOT
                (pyparsing.Optional("*", default='*'), 2, pyparsing.opAssoc.LEFT), #AND, including implied AND
                ("+", 2, pyparsing.opAssoc.LEFT), #OR
                ("^", 2, pyparsing.opAssoc.LEFT)  #XOR
            ]

        #define a new grammar in terms of the input terms and algebraic operators
        algebraExpresion = pyparsing.operatorPrecedence(inputTerms, algebraOperators)

        #use the newly created grammar to convert the boolean expression into an abstract syntax list
        try:
            ast = algebraExpresion.parseString(algebra_notation)[0]
        except pyparsing.ParseException, e:
            raise InvalidExpressionException("I couldn't figure out what you meant by '" + algebra_notation + "'.")
开发者ID:ktemkin,项目名称:logiclab,代码行数:30,代码来源:boolean_algebra.py


示例5: _query_expression

def _query_expression():
    operand = quotedString.setParseAction(removeQuotes)
    return operatorPrecedence(operand, [
        (CaselessLiteral('not'), 1, opAssoc.RIGHT, _not_expression),
        (CaselessLiteral('and'), 2, opAssoc.LEFT, _and_expression),
        (CaselessLiteral('or'), 2, opAssoc.LEFT, _or_expression)
    ])
开发者ID:eugeniy,项目名称:odatalastic,代码行数:7,代码来源:odata.py


示例6: _getParser

	def _getParser(self):
		if not self.parser:
			period = pp.Literal('.').suppress()
			lparen = pp.Literal('(').suppress()
			rparen = pp.Literal(')').suppress()
			forall = pp.Literal(self.symbols['forall'])
			exists = pp.Literal(self.symbols['exists'])
			bottom = pp.Literal(self.symbols['bottom'])
			top = pp.Literal(self.symbols['top'])
			
			uppers = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
			lowers = uppers.lower()
			
			conceptName = bottom | top | pp.Combine(pp.Word(uppers, exact=1) + pp.Word(pp.alphas))
			relationName = pp.Combine(pp.Word(lowers, exact=1) +  pp.Word(pp.alphas))
			valueOp = pp.Group(pp.Optional(forall | exists, default=forall) + relationName + period)
			dlExpression = pp.Forward()
			dlOperand = lparen + dlExpression + rparen | conceptName
			dlExpression << pp.operatorPrecedence(dlOperand,
				[
				(self.symbols['not'], 1, pp.opAssoc.RIGHT, ),
				(valueOp, 1, pp.opAssoc.RIGHT, ),
				(self.symbols['and'], 2, pp.opAssoc.LEFT, _toNested(2)),
				(self.symbols['or'], 2, pp.opAssoc.LEFT, _toNested(2)),
				])
			self.parser = dlExpression
		return self.parser
开发者ID:tyadams,项目名称:pythonDL,代码行数:27,代码来源:textexpressionparser.py


示例7: parse

 def parse(self):
     col = pp.Word(pp.alphanums)
     val = pp.Word(pp.alphanums)
     comp = pp.Regex("==|!=|<=|>=|<|>")
     cond = pp.Group(col + comp + val)
     expr = pp.operatorPrecedence(cond, [("&&", 2, pp.opAssoc.LEFT), ("||", 2, pp.opAssoc.LEFT)])
     return expr.parseString(self.cond).asList()[0]
开发者ID:Peratham,项目名称:ringo,代码行数:7,代码来源:cond.py


示例8: cross_link_db_filter_parser

def cross_link_db_filter_parser(inputstring):
    '''
    example '"{ID_Score}" > 28 AND "{Sample}" ==
     "%10_1%" OR ":Sample}" == "%10_2%" OR ":Sample}"
    == "%10_3%" OR ":Sample}" == "%8_1%" OR ":Sample}" == "%8_2%"'
    '''

    import pyparsing as pp

    operator = pp.Regex(">=|<=|!=|>|<|==|in").setName("operator")
    value = pp.QuotedString(
        '"') | pp.Regex(
        r"[+-]?\d+(:?\.\d*)?(:?[eE][+-]?\d+)?")
    identifier = pp.Word(pp.alphas, pp.alphanums + "_")
    comparison_term = identifier | value
    condition = pp.Group(comparison_term + operator + comparison_term)

    expr = pp.operatorPrecedence(condition, [
                                ("OR", 2, pp.opAssoc.LEFT, ),
        ("AND", 2, pp.opAssoc.LEFT, ),
    ])

    parsedstring = str(expr.parseString(inputstring)) \
        .replace("[", "(") \
        .replace("]", ")") \
        .replace(",", " ") \
        .replace("'", " ") \
        .replace("%", "'") \
        .replace("{", "float(entry['") \
        .replace("}", "'])") \
        .replace(":", "str(entry['") \
        .replace("}", "'])") \
        .replace("AND", "and") \
        .replace("OR", "or")
    return parsedstring
开发者ID:AljGaber,项目名称:imp,代码行数:35,代码来源:tools.py


示例9: get_grammar

def get_grammar():
    global _grammar
    if _grammar is None:
        from pyparsing import (Literal, Word, QuotedString, Optional, operatorPrecedence,
                               nums, alphas, opAssoc, ParseResults)

        # literals
        AND = Literal("AND")
        OR = Literal("OR")
        NOT = Literal("NOT")
        SPAN = (Literal("W/") + Word(nums).setResultsName("slop"))
        OP = Optional(AND | OR | NOT | SPAN, default="implicit_OR").setResultsName("operator")
            
        COLON = Literal(":").suppress()
        TILDE = Literal("~").suppress()
        LETTERS = u''.join(unichr(c) for c in xrange(65536) 
                           if not unichr(c).isspace() and unichr(c) not in '":()~')

        # terms
        term = Word(LETTERS)
        slop = Word(nums).setResultsName("slop")
        quote = QuotedString('"').setResultsName("quote") + Optional(TILDE + slop)
        #quote.setParseAction(Quote)

        field = Word(alphas).setResultsName("field")
        fterm = Optional(field + COLON) + (quote | term).setResultsName("term")
        fterm.setParseAction(get_term)

        # boolean combination
        boolean_expr = operatorPrecedence(fterm, [
            (OP, 2, opAssoc.LEFT)
            ])
        boolean_expr.setParseAction(get_boolean_or_term)
        _grammar = boolean_expr
    return _grammar
开发者ID:kasperwelbers,项目名称:amcat,代码行数:35,代码来源:queryparser.py


示例10: load_rules

def load_rules(filepath):
    operator = pp.Regex(">=|<=|!=|>|<|==").setName("operator")
    number = pp.Regex(r"[+-]?\d+(:?\.\d*)?(:?[eE][+-]?\d+)?")
    identifier = pp.Word(pp.alphas + "[]", pp.alphanums + "_[]")
    comparison_term = identifier | number
    a_comparison = comparison_term + operator + comparison_term
    stmt = a_comparison | identifier
    condition = pp.Group(stmt)
    
    expr = pp.operatorPrecedence(condition,[
                                ("NOT", 1, pp.opAssoc.RIGHT, ),
                                ("AND", 2, pp.opAssoc.LEFT, ),
                                ("OR", 2, pp.opAssoc.LEFT, ),
                                ])
    
    rules = []
    with open(filepath,'r') as f:
        lines = f.readlines()
        for line in lines:
            rule_and_acceptance = line.split("=>")
            ptree = expr.parseString(rule_and_acceptance[0].strip())
            acceptance = True if rule_and_acceptance[1].strip() == 'True' else False
            rules.append((json.loads(ptree[0].dump().replace("\'","\"")), acceptance)) # make flat list
            
    return rules
开发者ID:klyc0k,项目名称:EDSFilter,代码行数:25,代码来源:filterutils.py


示例11: get_parse_expression

def get_parse_expression(parse_func, parse_var_id):
    """return a parse expression with for the
    input parseActions
    """

    var_id = Group(FUNC_NAME + COLON + IDENTIFIER) | REAL | INTEGER | IDENTIFIER
    var_id.setParseAction(parse_var_id)

    # Forward declaration for an Arithmetic Expression
    arith_expr = Forward()
    func_call = Group(FUNC_NAME + LPAREN + Optional(Group(delimitedList(arith_expr))) + RPAREN)
    # An Arithmetic expression can have a var_id or
    # a function call as an operand
    # pylint: disable=expression-not-assigned
    arith_expr << operatorPrecedence(
        func_call | var_id,
        [
            (EXPONENTIATION_OPS, 2, opAssoc.LEFT, eval_binary_op),
            (UNARY_OPS, 1, opAssoc.RIGHT, eval_unary_op),
            (MULT_OPS, 2, opAssoc.LEFT, eval_binary_op),
            (SUM_OPS, 2, opAssoc.LEFT, eval_binary_op),
            (REL_OPS, 2, opAssoc.LEFT, eval_binary_op),
            (LOGICAL_OPS, 2, opAssoc.LEFT, eval_binary_op),
        ],
    )

    # pylint: enable=expression-not-assigned
    # Argument expression for a function call
    # An argument to a function can be an
    # IDENTIFIER, Arithmetic expression, REAL number, INTEGER or a
    # Function call itself
    func_call.setParseAction(parse_func)
    return arith_expr
开发者ID:ARM-software,项目名称:trappy,代码行数:33,代码来源:grammar.py


示例12: __init__

    def __init__(self):
        """
        BNF HERE
        """

        #integer = pp.Word(nums)
        #floatNumber = pp.Regex(r'\d+(\.\d*)?([eE]\d+)?')
        point = pp.Literal( "." )
        e     = pp.CaselessLiteral( "E" )

        # Regex string representing the set of possible operators
        # Example : ">=|<=|!=|>|<|="
        OPERATOR_RX = '|'.join([re.sub('\|', '\|', o) for o in Predicate.operators.keys()])

        # predicate
        field = pp.Word(pp.alphanums + '_')
        operator = pp.Regex(OPERATOR_RX).setName("operator")
        value = pp.QuotedString('"') #| pp.Combine( pp.Word( "+-"+ pp.nums, pp.nums) + pp.Optional( point + pp.Optional( pp.Word( pp.nums ) ) ) + pp.Optional( e + pp.Word( "+-"+pp.nums, pp.nums ) ) )

        predicate = (field + operator + value).setParseAction(self.handlePredicate)

        # clause of predicates
        and_op = pp.CaselessLiteral("and") | pp.Keyword("&&")
        or_op  = pp.CaselessLiteral("or")  | pp.Keyword("||")
        not_op = pp.Keyword("!")

        predicate_precedence_list = [
            (not_op, 1, pp.opAssoc.RIGHT, lambda x: self.handleClause(*x)),
            (and_op, 2, pp.opAssoc.LEFT,  lambda x: self.handleClause(*x)),
            (or_op,  2, pp.opAssoc.LEFT,  lambda x: self.handleClause(*x))
        ]
        clause = pp.operatorPrecedence(predicate, predicate_precedence_list)

        self.bnf = clause
开发者ID:AlexanderWillner,项目名称:myslice,代码行数:34,代码来源:clause.py


示例13: parser

def parser():
    global _parser
    if _parser is None:
        ParserElement.setDefaultWhitespaceChars("")
        lbrack, rbrack, lbrace, rbrace, lparen, rparen = 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)))
        reDot = Literal(".")
        repetition = (
                      (lbrace + Word(nums).setResultsName("count") + rbrace) |
                      (lbrace + Word(nums).setResultsName("minCount") + "," + Word(nums).setResultsName("maxCount") + rbrace) |
                      oneOf(list("*+?"))
                      )

        reRange.setParseAction(handle_range)
        reLiteral.setParseAction(handle_literal)
        reMacro.setParseAction(handle_macro)
        reDot.setParseAction(handle_dot)

        reTerm = (reLiteral | reRange | reMacro | reDot)
        reExpr = operatorPrecedence(reTerm, [
                (repetition, 1, opAssoc.LEFT, handle_repetition),
                (None, 2, opAssoc.LEFT, handle_sequence),
                (Suppress('|'), 2, opAssoc.LEFT, handle_alternative),
            ])

        _parser = reExpr

    return _parser
开发者ID:Bernie,项目名称:spyne,代码行数:34,代码来源:invregexp.py


示例14: _expression_parser

def _expression_parser():
    variable = Combine(Literal('?').suppress() + Word(alphas)) \
                .setParseAction(lambda s, loc, toks: VariableExpression(toks[0]))
    literal = _literal.copy().setParseAction(lambda s, loc, toks: LiteralExpression(toks[0]))
        
    value = variable | literal
    
    expr=Forward()
    exprList = delimitedList(expr)
    funcCall = (Word(alphas + "_") + \
                Literal('(').suppress() + \
                Optional(exprList) + \
                Literal(')').suppress()) .setParseAction(lambda s, loc, toks: FunctionCallExpression(toks[0], toks[1:]))
    baseExpr = funcCall | value
    
    expr << operatorPrecedence(baseExpr,[
        (oneOf('!'), 1, opAssoc.RIGHT, _unaryOpAction),
        (oneOf('+ -'), 1, opAssoc.RIGHT, _unaryOpAction),
        (oneOf('* /'), 2, opAssoc.LEFT, _binOpAction),
        (oneOf('+ -'), 2, opAssoc.LEFT, _binOpAction),
        (oneOf('<= >= < >'), 2, opAssoc.LEFT, _binOpAction),
        (oneOf('= !='), 2, opAssoc.LEFT, _binOpAction),
        ('&&', 2, opAssoc.LEFT, _binOpAction),
        ('||', 2, opAssoc.LEFT, _binOpAction),
    ])
    return (Literal('(').suppress() + expr + Literal(')').suppress()) | funcCall
开发者ID:lilspikey,项目名称:mini-sparql,代码行数:26,代码来源:minisparql.py


示例15: parse

def parse(formula):
    """Parse formula string and create abstract syntax tree (AST).
    """
    # LTL expression
    _ltl_expr = pp.operatorPrecedence(
        _proposition,
        [
            ("'", 1, pp.opAssoc.LEFT, ASTUnTempOp),
            ("!", 1, pp.opAssoc.RIGHT, ASTNot),
            (_UnaryTempOps, 1, pp.opAssoc.RIGHT, ASTUnTempOp),
            (pp.oneOf("& &&"), 2, pp.opAssoc.LEFT, ASTAnd),
            (pp.oneOf("| ||"), 2, pp.opAssoc.LEFT, ASTOr),
            (pp.oneOf("xor ^"), 2, pp.opAssoc.LEFT, ASTXor),
            ("->", 2, pp.opAssoc.RIGHT, ASTImp),
            ("<->", 2, pp.opAssoc.RIGHT, ASTBiImp),
            (pp.oneOf("= == !="), 2, pp.opAssoc.RIGHT, ASTComparator),
            (pp.oneOf("U V R"), 2, pp.opAssoc.RIGHT, ASTBiTempOp),
        ],
    )
    _ltl_expr.ignore(pp.LineStart() + "--" + pp.restOfLine)

    # Increase recursion limit for complex formulae
    sys.setrecursionlimit(2000)
    try:
        return _ltl_expr.parseString(formula, parseAll=True)[0]
    except RuntimeError:
        raise pp.ParseException("Maximum recursion depth exceeded," "could not parse")
开发者ID:rmattila,项目名称:tulip-control,代码行数:27,代码来源:pyparser.py


示例16: _parseFeatureSignature

def _parseFeatureSignature(sig):
    """This function parses a given feature-signature."""
    mal = set()

    def _rewriteOne(p):
        return ""

    def _rewriteTwo(p):
        return ""

    def _addIdentifier2Mal(p):
        mal.add(p[0])

    operand = __string | __hexadec | __function | __integer | __identifier.setParseAction(_addIdentifier2Mal)
    compoperator = pypa.oneOf("< > <= >= == !=")
    calcoperator = pypa.oneOf("+ - * / % & | << >>")
    expr = pypa.operatorPrecedence(
        operand,
        [
            ("defined", 1, pypa.opAssoc.RIGHT, _rewriteOne),
            ("!", 1, pypa.opAssoc.RIGHT, _rewriteOne),
            (calcoperator, 2, pypa.opAssoc.LEFT, _rewriteTwo),
            (compoperator, 2, pypa.opAssoc.LEFT, _rewriteTwo),
            ("&&", 2, pypa.opAssoc.LEFT, _rewriteTwo),
            ("||", 2, pypa.opAssoc.LEFT, _rewriteTwo),
        ],
    )

    try:
        rsig = expr.parseString(sig)[0]
    except pypa.ParseException, e:
        print("ERROR (parse): cannot parse sig (%s) -- (%s)" % (sig, e.col))
        return sig
开发者ID:pombredanne,项目名称:cppstats,代码行数:33,代码来源:derivative.py


示例17: parse_prereq_text

def parse_prereq_text(text):
	number = pp.Regex(r"\d+")
	expr = pp.operatorPrecedence(number, [
			("&&", 2, pp.opAssoc.LEFT, ),
			("||", 2, pp.opAssoc.LEFT, ),
		])
	return expr.parseString(text)
开发者ID:fi-ksi,项目名称:web-backend,代码行数:7,代码来源:taskDeploy.py


示例18: parse

    def parse(self, request):
        input = request._rest_context.get('filter')
        if not input:
            return None

        condition_positions = []

        operator = pp.Regex('|'.join(self.ALLOWED_OPERATORS))
        number = pp.Regex(r"[+-]?\d+(:?\.\d*)?(:?[eE][+-]?\d+)?")

        AND = pp.Literal(LOGICAL_OPERATORS.AND)
        OR = pp.Literal(LOGICAL_OPERATORS.OR)
        NOT = pp.Literal(LOGICAL_OPERATORS.NOT)

        identifier = pp.Regex(r"[a-zA-Z]+[a-zA-Z0-9]*(_[a-zA-Z0-9]+)*")
        identifiers = pp.Group(pp.delimitedList(identifier, delim="__", combine=False))

        comparison_term = pp.Forward()
        list_term = (
            pp.Group(
                pp.Suppress('[') + pp.delimitedList(comparison_term, delim=",", combine=False) + pp.Suppress(']')
            ) |
            pp.Group(
                pp.Suppress('(') + pp.delimitedList(comparison_term, delim=",", combine=False) + pp.Suppress(')')
            ) |
            pp.Group(
                pp.Suppress('{') + pp.delimitedList(comparison_term, delim=",", combine=False) + pp.Suppress('}')
            )
        )
        string = (
            pp.QuotedString("'", escChar='\\', unquoteResults=True) | pp.QuotedString('"', escChar='\\',
                                                                                      unquoteResults=True)
        )
        null = pp.Literal('null').setParseAction(lambda s,l,t: None)
        boolean = pp.Regex('|'.join(('true', 'false'))).setParseAction(lambda s, l, t: t[0] == 'true')

        comparison_term << (string | number | list_term | null | boolean)

        condition = pp.Group(identifiers + operator + comparison_term).setResultsName('condition')
        condition.setParseAction(lambda s, loc, tocs: condition_positions.append(loc))

        expr = pp.operatorPrecedence(
            condition, [
                (NOT, 1, pp.opAssoc.RIGHT,),
                (AND, 2, pp.opAssoc.LEFT,),
                (OR, 2, pp.opAssoc.LEFT,),
            ]
        )

        try:
            return self._parse_to_conditions(
                expr.parseString(input, parseAll=True).asList()[0], list(condition_positions), condition, input
            )
        except pp.ParseException as ex:
            raise FilterParserError(
                mark_safe(ugettext('Invalid filter value "{}"').format(input))
            )
开发者ID:rubickcz,项目名称:django-pyston,代码行数:57,代码来源:parser.py


示例19: __init__

	def __init__(self, fields):
		self._word = pyparsing.Word(QueryParser._wordchars)
		self._word.setParseAction(partial(self._parse_word, fields))
		self._phrase = pyparsing.QuotedString('"', '\\')
		self._phrase.setParseAction(partial(self._parse_phrase, fields))
		self._token = self._phrase | self._word
		self._query = pyparsing.Forward()
		self._query << pyparsing.operatorPrecedence(self._token, [
			QueryParser._not_op, QueryParser._and_op, QueryParser._or_op])
		self._multiword = pyparsing.OneOrMore(self._word)
		self._multiword.setParseAction(self._parse_multi)
开发者ID:3taps,项目名称:3TapsSearchDB,代码行数:11,代码来源:search.py


示例20: conditions

 def conditions(self):
     """
     conditions ::= condition | condition logical_binary_op conditions
     Note: By default lpar and rpar arguments are suppressed.
     """
     return operatorPrecedence(
         baseExpr=self.condition,
         opList=[(self.not_op, 1, opAssoc.RIGHT),
                 (self.logical_binary_op, 2, opAssoc.LEFT)],
         lpar=self.syntax.paren_left,
         rpar=self.syntax.paren_right)
开发者ID:pyrapt,项目名称:rapt,代码行数:11,代码来源:condition_grammar.py



注:本文中的pyparsing.operatorPrecedence函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python pyparsing.replaceWith函数代码示例发布时间:2022-05-27
下一篇:
Python pyparsing.oneOf函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap