当前位置: 首页>>代码示例>>Python>>正文


Python Combine.setParseAction方法代码示例

本文整理汇总了Python中pyparsing.Combine.setParseAction方法的典型用法代码示例。如果您正苦于以下问题:Python Combine.setParseAction方法的具体用法?Python Combine.setParseAction怎么用?Python Combine.setParseAction使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在pyparsing.Combine的用法示例。


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

示例1: parser

# 需要导入模块: from pyparsing import Combine [as 别名]
# 或者: from pyparsing.Combine import setParseAction [as 别名]
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,代码行数:36,代码来源:invregexp.py

示例2: define_number

# 需要导入模块: from pyparsing import Combine [as 别名]
# 或者: from pyparsing.Combine import setParseAction [as 别名]
 def define_number(self):
     """
     Return the syntax definition for a number in Arabic Numerals.
     
     Override this method to support numeral systems other than Arabic
     Numerals (0-9).
     
     Do not override this method just to change the character used to
     separate thousands and decimals: Use :attr:`T_THOUSANDS_SEPARATOR`
     and :attr:`T_DECIMAL_SEPARATOR`, respectively.
     
     """
     # Defining the basic tokens:
     to_dot = lambda t: "."
     to_plus = lambda t: "+"
     to_minus = lambda t: "-"
     positive_sign = Literal(self._grammar.get_token("positive_sign"))
     positive_sign.setParseAction(to_plus)
     negative_sign = Literal(self._grammar.get_token("negative_sign"))
     negative_sign.setParseAction(to_minus)
     decimal_sep = Literal(self._grammar.get_token("decimal_separator"))
     decimal_sep.setParseAction(to_dot)
     thousands_sep = Suppress(self._grammar.get_token("thousands_separator"))
     digits = Word(nums)
     # Building the integers and decimals:
     sign = positive_sign | negative_sign
     thousands = Word(nums, max=3) + \
                 OneOrMore(thousands_sep + Word(nums, exact=3))
     integers = thousands | digits
     decimals = decimal_sep + digits
     number = Combine(Optional(sign) + integers + Optional(decimals))
     number.setParseAction(self.make_number)
     number.setName("number")
     return number
开发者ID:aipub,项目名称:booleano,代码行数:36,代码来源:parsers.py

示例3: func_tokens

# 需要导入模块: from pyparsing import Combine [as 别名]
# 或者: from pyparsing.Combine import setParseAction [as 别名]
def func_tokens(dictionary, parse_action):
    func_name = Word(alphas+'_', alphanums+'_')

    func_ident = Combine('$' + func_name.copy()('funcname'))
    func_tok = func_ident + originalTextFor(nestedExpr())('args')
    func_tok.leaveWhitespace()
    func_tok.setParseAction(parse_action)
    func_tok.enablePackrat()

    rx_tok = Combine(Literal('$').suppress() + Word(nums)('num'))

    def replace_token(tokens):
        index = int(tokens.num)
        return dictionary.get(index, u'')

    rx_tok.setParseAction(replace_token)

    strip = lambda s, l, tok: tok[0].strip()
    text_tok = CharsNotIn(u',').setParseAction(strip)
    quote_tok = QuotedString('"')

    if dictionary:
        arglist = Optional(delimitedList(quote_tok | rx_tok | text_tok))
    else:
        arglist = Optional(delimitedList(quote_tok | text_tok))

    return func_tok, arglist, rx_tok
开发者ID:frnogueira,项目名称:puddletag,代码行数:29,代码来源:findfunc.py

示例4: _BNF

# 需要导入模块: from pyparsing import Combine [as 别名]
# 或者: from pyparsing.Combine import setParseAction [as 别名]
    def _BNF(self):
        base16 = Literal("$")
        hex = Combine(base16 + Word(hexnums + "_"))

        base4 = Literal("%%")
        quaternary = Combine(base4 + Word("0123_"))

        base2 = Literal("%")
        binary = Combine(base2 + Word("01_"))

        plusminus = Literal("+") | Literal("-")
        integer = Combine(Optional(plusminus) + Word(nums+"_"))

        name_token = Combine(Optional(Literal(":") | Literal("@")) + Word("_" + alphas, "_" + alphanums))
        name_token.setParseAction(self._mark_name_token)

        lparens = Literal("(").suppress()
        rparens = Literal(")").suppress()

        # op0 = Literal("@")
        op1 = (Literal("^^") | Literal("||") | Literal("|<") | Literal(">|") | Literal("!")).setParseAction(self._mark_unary)
        op2 = Literal("->") | Literal("<-") | Literal(">>") | Literal("<<") | Literal("~>") | Literal("><")
        op3 = Literal("&")
        op4 = Literal("|") | Literal("^")
        op5 = Literal("**") | Literal("*") | Literal("//") | Literal("/")
        op6 = Literal("+") | Literal("-")
        op7 = Literal("#>") | Literal("<#")
        op8 = Literal("<") | Literal(">") | Literal("<>") | Literal("==") | Literal("=<") | Literal("=>")
        op9 = Literal("NOT").setParseAction(self._mark_unary)
        op10 = Literal("AND")
        op11 = Literal("OR")
        op12 = Literal(",")

        expr = Forward()

        atom = name_token | hex | quaternary | binary | integer | quotedString
        atom.setParseAction(self._push)
        atom = atom | (lparens + expr.suppress() + rparens)
 
        # term0  = atom   + ZeroOrMore((op0 + atom)   .setParseAction(self._push))
        # term1  = term0  + ZeroOrMore((op1 + term0)  .setParseAction(self._push))
        term1  = atom   + ZeroOrMore((op1 + atom)   .setParseAction(self._push))
        term2  = term1  + ZeroOrMore((op2 + term1)  .setParseAction(self._push))
        term3  = term2  + ZeroOrMore((op3 + term2)  .setParseAction(self._push))
        term4  = term3  + ZeroOrMore((op4 + term3)  .setParseAction(self._push))
        term5  = term4  + ZeroOrMore((op5 + term4)  .setParseAction(self._push))
        term6  = term5  + ZeroOrMore((op6 + term5)  .setParseAction(self._push))
        term7  = term6  + ZeroOrMore((op7 + term6)  .setParseAction(self._push))
        term8  = term7  + ZeroOrMore((op8 + term7)  .setParseAction(self._push))
        term9  = term8  + ZeroOrMore((op9 + term8)  .setParseAction(self._push))
        term10 = term9  + ZeroOrMore((op10 + term9) .setParseAction(self._push))
        term11 = term10 + ZeroOrMore((op11 + term10).setParseAction(self._push))
        expr  << term11 + ZeroOrMore((op12 + term11).setParseAction(self._push))

        return expr
开发者ID:Seairth,项目名称:Orochi,代码行数:57,代码来源:expression.py

示例5: getkw_bnf

# 需要导入模块: from pyparsing import Combine [as 别名]
# 或者: from pyparsing.Combine import setParseAction [as 别名]
	def getkw_bnf(self):
		sect_begin   = Literal("{").suppress()
		sect_end   = Literal("}").suppress()
		array_begin   = Literal("[").suppress()
		array_end   = Literal("]").suppress()
		tag_begin   = Literal("<").suppress()
		tag_end   = Literal(">").suppress()
		eql   = Literal("=").suppress()
		dmark = Literal('$').suppress()
		end_data=Literal('$end').suppress()
		prtable = alphanums+r'!$%&*+-./<>[email protected]^_|~'
		ival=Regex('[-]?\d+')
		dval=Regex('-?\d+\.\d*([eE]?[+-]?\d+)?')
		lval=Regex('([Yy]es|[Nn]o|[Tt]rue|[Ff]alse|[Oo]n|[Oo]ff)')
	
		# Helper definitions

		kstr= quotedString.setParseAction(removeQuotes) ^ \
				dval ^ ival ^ lval ^ Word(prtable)
		name = Word(alphas+"_",alphanums+"_")
		vec=array_begin+delimitedList(dval ^ ival ^ lval ^ Word(prtable) ^ \
				Literal("\n").suppress() ^ \
				quotedString.setParseAction(removeQuotes))+array_end
		sect=name+sect_begin
		tag_sect=name+Group(tag_begin+name+tag_end)+sect_begin

		# Grammar
		keyword = name + eql + kstr
		vector = name + eql + vec
		data=Combine(dmark+name)+SkipTo(end_data)+end_data
		section=Forward()
		sect_def=(sect | tag_sect ) #| vec_sect)
		input=section | data | vector | keyword 
		section << sect_def+ZeroOrMore(input) + sect_end

		# Parsing actions	
		ival.setParseAction(self.conv_ival)
		dval.setParseAction(self.conv_dval)
		lval.setParseAction(self.conv_lval)
		keyword.setParseAction(self.store_key)
		vector.setParseAction(self.store_vector)
		data.setParseAction(self.store_data)
		sect.setParseAction(self.add_sect)
		tag_sect.setParseAction(self.add_sect)
		sect_end.setParseAction(self.pop_sect)

		bnf=ZeroOrMore(input) + StringEnd().setFailAction(parse_error)
		bnf.ignore(pythonStyleComment)
		return bnf
开发者ID:juselius,项目名称:libgetkw,代码行数:51,代码来源:getkw.py

示例6: parser

# 需要导入模块: from pyparsing import Combine [as 别名]
# 或者: from pyparsing.Combine import setParseAction [as 别名]
def parser():
    global _parser
    if _parser is None:
        ParserElement.setDefaultWhitespaceChars("")
        
        lbrack = Literal("[")
        rbrack = Literal("]")
        lbrace = Literal("{")
        rbrace = Literal("}")
        lparen = Literal("(")
        rparen = Literal(")")
        
        reMacro = Suppress("\\") + oneOf(list("dwsZ"))
        escapedChar = ~reMacro + Combine("\\" + oneOf(list(printables)))
        reLiteralChar = "".join(c for c in string.printable if c not in r"\[]{}().*?+|")

        reRange = Combine(lbrack.suppress() + SkipTo(rbrack,ignore=escapedChar) + rbrack.suppress())
        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("*+?"))
            )
        reExpr = Forward()
        reGroup = (lparen.suppress() +
                   Optional(Literal("?").suppress() + oneOf(list(":P"))).setResultsName("option") +
                   reExpr.setResultsName("expr") +
                   rparen.suppress())

        reTerm = ( reLiteral | reRange | reMacro | reDot | reGroup )
        reExpr << operatorPrecedence( reTerm,
            [
            (repetition, 1, opAssoc.LEFT, create(Repetition)),
            (None, 2, opAssoc.LEFT, create(Sequence)),
            (Suppress('|'), 2, opAssoc.LEFT, create(Alternation)),
            ]
            )

        reGroup.setParseAction(create(Group))
        reRange.setParseAction(create(Range))
        reLiteral.setParseAction(create(Character))
        reMacro.setParseAction(create(Macro))
        reDot.setParseAction(create(Dot))
        
        _parser = reExpr
        
    return _parser
开发者ID:GunioRobot,项目名称:pycucumber,代码行数:50,代码来源:regex_parser.py

示例7: grammar

# 需要导入模块: from pyparsing import Combine [as 别名]
# 或者: from pyparsing.Combine import setParseAction [as 别名]
    def grammar(self):
        number = Combine(Word(nums) + Optional("." + OneOrMore(Word(nums))))
        table = Combine(Word(alphas) + OneOrMore(Word("_"+alphanums)))

        number.setParseAction(self._number_parse_action)
        table.setParseAction(self._table_parse_action)

        signop = oneOf('+ -')
        multop = oneOf('* /')
        plusop = oneOf('+ -')

        operand = number | table

        return operatorPrecedence(operand, [
            (signop, 1, opAssoc.RIGHT),
            (multop, 2, opAssoc.LEFT),
            (plusop, 2, opAssoc.LEFT)
        ])
开发者ID:peterlandry,项目名称:django-census,代码行数:20,代码来源:parse.py

示例8: getkw_bnf

# 需要导入模块: from pyparsing import Combine [as 别名]
# 或者: from pyparsing.Combine import setParseAction [as 别名]
	def getkw_bnf(self):
		sect_begin   = Literal("{").suppress()
		sect_end   = Literal("}").suppress()
		array_begin   = Literal("[").suppress()
		array_end   = Literal("]").suppress()
		arg_begin   = Literal("(").suppress()
		arg_end   = Literal(")").suppress()
		eql   = Literal("=").suppress()
		dmark = Literal('$').suppress()
		end_data=Literal('$end').suppress()
		prtable = alphanums+r'!$%&*+-./<>[email protected]^_|~'

	
		# Helper definitions
		kstr=Word(prtable) ^ quotedString.setParseAction(removeQuotes)
		name = Word(alphas+"_",alphanums+"_")
		vec=array_begin+delimitedList(Word(prtable) ^ \
				Literal("\n").suppress() ^ \
				quotedString.setParseAction(removeQuotes))+array_end
		sect=name+sect_begin
		key_sect=name+Group(arg_begin+kstr+arg_end)+sect_begin
		vec_sect=name+Group(arg_begin+vec+ arg_end)+sect_begin

		# Grammar
		keyword = name + eql + kstr
		vector = name + eql + vec
		data=Combine(dmark+name)+SkipTo(end_data)+end_data
		section=Forward()
		sect_def=(sect | key_sect | vec_sect)
		input=section | data | vector | keyword 
		section << sect_def+ZeroOrMore(input) + sect_end

		# Parsing actions	
		keyword.setParseAction(self.store_key)
		vector.setParseAction(self.store_vector)
		data.setParseAction(self.store_data)
		sect.setParseAction(self.add_sect)
		key_sect.setParseAction(self.add_sect)
		vec_sect.setParseAction(self.add_vecsect)
		sect_end.setParseAction(self.pop_sect)

		bnf=ZeroOrMore(input) + StringEnd().setFailAction(parse_error)
		bnf.ignore(pythonStyleComment)
		return bnf
开发者ID:juselius,项目名称:gimic,代码行数:46,代码来源:getkw.py

示例9: _build_grammar

# 需要导入模块: from pyparsing import Combine [as 别名]
# 或者: from pyparsing.Combine import setParseAction [as 别名]
    def _build_grammar(self):
        expr = Forward()

        float_lit = Combine(Word(nums) + '.' + Word(nums))
        float_lit.setName('float')
        float_lit.setParseAction(lambda x: \
                                     self.to_literal(float(x[0])))

        int_lit = Word(nums)
        int_lit.setName('int')
        int_lit.setParseAction(lambda x: \
                                   self.to_literal(int(x[0])))

        num = (float_lit | int_lit)
        num.setParseAction(lambda x: x[0])

        tag_name = Word(alphas + "_", alphanums + "_")
        tag_name.setName('tag_name')
        tag_name.setParseAction(lambda t: tag_reference.TagReference(t[0]))

        quoted_string = QuotedString("'")
        quoted_string.setParseAction(lambda s: self.to_literal(s[0]))

        oper = oneOf('+ * / -')
        oper.setParseAction(lambda o: o[0])

        lpar  = Literal("(").suppress()
        rpar  = Literal(")").suppress()

        arith = Group(lpar + expr + oper + expr + rpar)
        arith.setParseAction(lambda t: \
                                 self.to_arith(t[0][0], t[0][1], t[0][2]))

        assign = tag_name + '=' + expr
        assign.setName('assign')
        assign.setParseAction(lambda x: self.to_assign(x[0],x[2]))

        print_tags = Literal('?')
        print_tags.setParseAction(lambda x: self.to_print_tags())

        expr <<(arith|assign|tag_name|num|quoted_string|print_tags)
        expr.setParseAction(lambda x: x[0])
        return expr
开发者ID:diegov,项目名称:retag,代码行数:45,代码来源:dsl_engine.py

示例10: create_bnf

# 需要导入模块: from pyparsing import Combine [as 别名]
# 或者: from pyparsing.Combine import setParseAction [as 别名]
def create_bnf():
    cvt_int = lambda toks: int(toks[0])
    cvt_real = lambda toks: float(toks[0])
    cvt_tuple = lambda toks : tuple(toks.asList())
    cvt_dict = lambda toks: dict(toks.asList())

    # define punctuation as suppressed literals
    (lparen, rparen, lbrack, rbrack,
     lbrace, rbrace, colon) = map(Suppress,"()[]{}:")

    integer = Combine(Optional(oneOf("+ -")) + Word(nums)).setName("integer")
    integer.setParseAction(cvt_int)

    real = Combine(Optional(oneOf("+ -"))+ Word(nums)
                   + "." + Optional(Word(nums))
                   + Optional("e" + Optional(oneOf("+ -"))
                              + Word(nums))).setName("real")
    real.setParseAction(cvt_real)

    tuple_str = Forward()
    list_str = Forward()
    dict_str = Forward()

    list_item = (real | integer | Group(list_str) | tuple_str | dict_str
                 | quotedString.setParseAction(removeQuotes)
                 | Word(alphas8bit + alphas, alphas8bit + alphanums + "_"))
    list_item2 = list_item | Empty().setParseAction(lambda: [None])

    tuple_str << (Suppress("(") + Optional(delimitedList(list_item)) +
                  Optional(Suppress(",")) + Suppress(")"))
    tuple_str.setParseAction(cvt_tuple)

    list_str << (lbrack + Optional(delimitedList(list_item) +
                                   Optional(Suppress(","))) + rbrack)

    dict_entry = Group(list_item + colon + list_item2)
    dict_inner = delimitedList(dict_entry) + Optional(Suppress(","))
    dict_inner.setParseAction(cvt_dict)

    dict_str << (lbrace + Optional(dict_inner) + rbrace)

    return dict_inner
开发者ID:renatocoutinho,项目名称:sfepy,代码行数:44,代码来源:parse_conf.py

示例11: pattern

# 需要导入模块: from pyparsing import Combine [as 别名]
# 或者: from pyparsing.Combine import setParseAction [as 别名]
    def pattern():
        """pyparsing pattern
        """
        
        def attachLocation(s, loc, tocs):
            """pyparsing callback. Saves path position in the original string
            """
            return [(loc, tocs[0])]

        path = CharsNotIn(" \t")("path")
        path.setParseAction(attachLocation)
        longPath = CharsNotIn(" \t", min=2)("path")
        longPath.setParseAction(attachLocation)
        slashPath = Combine(Literal('/') + Optional(CharsNotIn(" \t")))("path")
        slashPath.setParseAction(attachLocation)

        pat = ((Literal('f ') + Optional(White()) + Optional(path)) ^ longPath ^ slashPath) + \
                    Optional(White() + Word(nums)("line"))
        pat.leaveWhitespace()
        pat.setParseAction(CommandOpen.create)
        return pat
开发者ID:hlamer,项目名称:completer,代码行数:23,代码来源:workspace_commands.py

示例12: parser

# 需要导入模块: from pyparsing import Combine [as 别名]
# 或者: from pyparsing.Combine import setParseAction [as 别名]
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)("count") + rbrace ) |
            ( lbrace + Word(nums)("minCount")+","+ Word(nums)("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:vmuriart,项目名称:pyparsing,代码行数:38,代码来源:invRegex.py

示例13: Word

# 需要导入模块: from pyparsing import Combine [as 别名]
# 或者: from pyparsing.Combine import setParseAction [as 别名]
    return query


NO_BRTS = printables.replace('(', '').replace(')', '')
SINGLE = Word(NO_BRTS.replace('*', ''))
WILDCARDS = Optional('*') + SINGLE + Optional('*') + WordEnd(wordChars=NO_BRTS)
QUOTED = quotedString.setParseAction(removeQuotes)

OPER_AND = CaselessLiteral('and')
OPER_OR = CaselessLiteral('or')
OPER_NOT = '-'

TERM = Combine(Optional(Word(alphas).setResultsName('meta') + ':') +
               (QUOTED.setResultsName('query') |
                WILDCARDS.setResultsName('query')))
TERM.setParseAction(createQ)

EXPRESSION = operatorPrecedence(TERM, [
    (OPER_NOT, 1, opAssoc.RIGHT),
    (OPER_OR, 2, opAssoc.LEFT),
    (Optional(OPER_AND, default='and'), 2, opAssoc.LEFT)])
EXPRESSION.setParseAction(unionQ)

QUERY = OneOrMore(EXPRESSION) + StringEnd()
QUERY.setParseAction(unionQ)


def advanced_search(pattern):
    """Parse the grammar of a pattern
    and build a queryset with it"""
    query_parsed = QUERY.parseString(pattern)
开发者ID:Big-Data,项目名称:gnowsys-studio,代码行数:33,代码来源:search.py

示例14: __init__

# 需要导入模块: from pyparsing import Combine [as 别名]
# 或者: from pyparsing.Combine import setParseAction [as 别名]

#.........这里部分代码省略.........
                     "var": xr.DataArray.var}

        # Define non-xarray DataArray operators with 2 input parameter
        self.xcond = {"<": np.percentile}

        # Define Grammar
        point = Literal(".")
        e = CaselessLiteral("E")
        fnumber = Combine(Word("+-"+nums, nums) +
                          Optional(point + Optional(Word(nums))) +
                          Optional(e + Word("+-"+nums, nums)))
        variable = Word(alphas, alphas+nums+"_$")

        seq = Literal("=")
        b_not = Literal("~")
        plus = Literal("+")
        minus = Literal("-")
        mult = Literal("*")
        div = Literal("/")
        gt = Literal(">")
        gte = Literal(">=")
        lt = Literal("<")
        lte = Literal("<=")
        eq = Literal("==")
        neq = Literal("!=")
        b_or = Literal("|")
        b_and = Literal("&")
        l_not = Literal("!")
        lpar = Literal("(").suppress()
        rpar = Literal(")").suppress()
        comma = Literal(",")
        colon = Literal(":")
        lbrac = Literal("[")
        rbrac = Literal("]")
        lcurl = Literal("{")
        rcurl = Literal("}")
        qmark = Literal("?")
        scolon = Literal(";")
        addop = plus | minus
        multop = mult | div
        sliceop = colon
        compop = gte | lte | gt | lt
        eqop = eq | neq
        bitcompop = b_or | b_and
        bitnotop = b_not
        logicalnotop = l_not
        assignop = seq
        expop = Literal("^")

        expr = Forward()
        indexexpr = Forward()

        atom = (Optional("-") +
                (variable + seq + expr).setParseAction(self.push_assign) |
                indexexpr.setParseAction(self.push_index) |
                (lpar + expr + qmark.setParseAction(self.push_ternary1) + expr +
                 scolon.setParseAction(self.push_ternary2) + expr +
                 rpar).setParseAction(self.push_ternary) |
                (lpar + expr + qmark + expr + scolon + expr +
                 rpar).setParseAction(self.push_ternary) |
                (logicalnotop + expr).setParseAction(self.push_ulnot) |
                (bitnotop + expr).setParseAction(self.push_unot) |
                (minus + expr).setParseAction(self.push_uminus) |
                (variable + lcurl + expr +
                 rcurl).setParseAction(self.push_mask) |
                (variable + lpar + expr + (comma + expr)*3 +
                 rpar).setParseAction(self.push_expr4) |
                (variable + lpar + expr + (comma + expr)*2 +
                 rpar).setParseAction(self.push_expr3) |
                (variable + lpar + expr + comma + expr +
                 rpar).setParseAction(self.push_expr2) |
                (variable + lpar + expr + rpar |
                 variable).setParseAction(self.push_expr1) |
                fnumber.setParseAction(self.push_expr) |
                (lpar + expr + ZeroOrMore(comma + expr).setParseAction(self.get_tuple) +
                 rpar).setParseAction(self.push_tuple) |
                (lpar + expr.suppress() +
                 rpar).setParseAction(self.push_uminus))

        # Define order of operations for operators

        factor = Forward()
        factor << atom + ZeroOrMore((expop + factor).setParseAction(self.push_op))
        term = factor + ZeroOrMore((multop + factor).setParseAction(self.push_op))
        term2 = term + ZeroOrMore((addop + term).setParseAction(self.push_op))
        term3 = term2 + ZeroOrMore((sliceop + term2).setParseAction(self.push_op))
        term4 = term3 + ZeroOrMore((compop + term3).setParseAction(self.push_op))
        term5 = term4 + ZeroOrMore((eqop + term4).setParseAction(self.push_op))
        term6 = term5 + ZeroOrMore((bitcompop + term5).setParseAction(self.push_op))
        expr << term6 + ZeroOrMore((assignop + term6).setParseAction(self.push_op))

        # Define index operators

        colon_expr = (colon + FollowedBy(comma) ^ colon +
                      FollowedBy(rbrac)).setParseAction(self.push_colon)
        range_expr = colon_expr | expr | colon
        indexexpr << (variable + lbrac + delimitedList(range_expr, delim=',') +
                      rbrac).setParseAction(self.push_expr)

        self.parser = expr
开发者ID:prasunkgupta,项目名称:datacube-iirs,代码行数:104,代码来源:__init__.py

示例15: transform_human

# 需要导入模块: from pyparsing import Combine [as 别名]
# 或者: from pyparsing.Combine import setParseAction [as 别名]
def transform_human(text, variables=None):
    """Transform user input with given context.

    Args:
        text (str): User input.
        variables (dict): Variables for purposes of substitution.

    Returns:
        A 2-tuple of: (A human-readable script that Script can parse,
            A list of contextual information for tooltips, etc.)
    """
    if variables is None:
        variables = {} # No mutable default value.
    # these are parseActions for pyparsing.
    def str_literal_to_hex(s, loc, toks):
        for i, t in enumerate(toks):
            toks[i] = ''.join(['0x', t.encode('hex')])
        return toks
    def var_name_to_value(s, loc, toks):
        for i, t in enumerate(toks):
            val = variables.get(t[1:])
            if val:
                toks[i] = val
        return toks
    def implicit_opcode_to_explicit(s, loc, toks):
        """Add "OP_" prefix to an opcode."""
        for i, t in enumerate(toks):
            toks[i] = '_'.join(['OP', t])
        return toks
    def hex_to_formatted_hex(s, loc, toks):
        """Add "0x" prefix and ensure even length."""
        for i, t in enumerate(toks):
            new_tok = t
            # Add '0x' prefix
            if not t.startswith('0x'):
                if t.startswith('x'):
                    new_tok = ''.join(['0', t])
                else:
                    new_tok = ''.join(['0x', t])
            # Even-length string
            if len(new_tok) % 2 != 0:
                new_tok = ''.join([new_tok[0:2], '0', new_tok[2:]])
            toks[i] = new_tok
        return toks
    # ^ parseActions for pyparsing end here.
    str_literal = QuotedString('"')
    str_literal.setParseAction(str_literal_to_hex)
    var_name = Combine(Word('$') + Word(pyparsing.alphas))
    var_name.setParseAction(var_name_to_value)

    # Here we populate the list of contextual tips.

    # Explicit opcode names
    op_names = [str(i) for i in OPCODE_NAMES.keys()]
    op_names_explicit = ' '.join(op_names)
    def is_small_int(op):
        """True if op is one of OP_1, OP_2, ...OP_16"""
        try:
            i = int(op[3:])
            return True
        except ValueError:
            return False
    op_names_implicit = ' '.join([i[3:] for i in op_names if not is_small_int(i)])

    # Hex, implicit (e.g. 'a') and explicit (e.g. '0x0a')
    explicit_hex = Combine(Word('0x') + Word(pyparsing.hexnums) + pyparsing.WordEnd())
    implicit_hex = Combine(pyparsing.WordStart() + OneOrMore(Word(pyparsing.hexnums)) + pyparsing.WordEnd())
    explicit_hex.setParseAction(hex_to_formatted_hex)
    implicit_hex.setParseAction(hex_to_formatted_hex)

    # Opcodes, implicit (e.g. 'ADD') and explicit (e.g. 'OP_ADD')
    explicit_op = pyparsing.oneOf(op_names_explicit)
    implicit_op = Combine(pyparsing.WordStart() + pyparsing.oneOf(op_names_implicit))
    implicit_op.setParseAction(implicit_opcode_to_explicit)

    contexts = pyparsing.Optional(var_name('Variable') |
                                  str_literal('String literal') |
                                  explicit_op('Opcode') |
                                  implicit_op('Opcode') |
                                  explicit_hex('Hex') |
                                  implicit_hex('Hex'))
    matches = [(i[0].asDict(), i[1], i[2]) for i in contexts.scanString(text)]
    context_tips = []
    for i in matches:
        d = i[0]
        if len(d.items()) == 0: continue
        match_type, value = d.items()[0]
        start = i[1]
        end = i[2]
        context_tips.append( (start, end, value, match_type) )

    # Now we do the actual transformation.

    s = text
    s = var_name.transformString(s)
    s = str_literal.transformString(s)
    s = implicit_op.transformString(s)
    s = implicit_hex.transformString(s)
    s = explicit_hex.transformString(s)
    return s, context_tips
开发者ID:aesedepece,项目名称:hashmal,代码行数:102,代码来源:script.py


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