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


Python Word.copy方法代码示例

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


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

示例1: __init__

# 需要导入模块: from pyparsing import Word [as 别名]
# 或者: from pyparsing.Word import copy [as 别名]
    def __init__(self):
        # literals
        star = Literal('*')
        comma = Suppress(',')

        # indentifiers
        identifier = Word(alphas, alphanums+'_')
        alias      = identifier.copy()

        # select clause
        column_name = Combine(Optional(alias + '.') +
                              identifier +
                              Optional(' as ' + identifier))\
                              .setResultsName('column_name')
        select = Keyword('select', caseless=1)
        select_clause = (star | Group(delimitedList(column_name, comma)))\
            .setResultsName('select_clause')

        # from clause
        from_  = Keyword('from', caseless=1)
        table_name =  delimitedList(identifier + Optional(alias), comma)
        from_clause = table_name.setResultsName('from_clause')

        # select statment
        self.select_stmt = select + select_clause + from_ + from_clause
开发者ID:dlink,项目名称:sqlparser,代码行数:27,代码来源:sqlparser.py

示例2: func_tokens

# 需要导入模块: from pyparsing import Word [as 别名]
# 或者: from pyparsing.Word import copy [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

示例3: make_parser

# 需要导入模块: from pyparsing import Word [as 别名]
# 或者: from pyparsing.Word import copy [as 别名]
	def make_parser(self):
		g = self
		
		lpar = Literal('(').suppress()
		rpar = Literal(')').suppress()
		colon = Literal(':').suppress()
		delimiter = Literal(';').suppress()
		unknown = Literal('?').setParseAction(lambda s,l,t: [0])  # ? -> number 0
		
		number = Word(nums).setParseAction(map_int)

		ident = Word(alphas+'_', alphas+nums+'_')

		label_gen = (
			ident + lpar + Optional(number) + rpar
		).setParseAction(tokenize('LabelGen'))

		label_def = (ident + colon).setParseAction(tokenize('LabelDef'), run(g.gen_label_def))

		label_ref = ident.copy().setParseAction(tokenize('LabelRef'))

		operand = number | label_gen | label_ref | unknown

		instr = (ident + List(operand) + delimiter).setParseAction(tokenize('Instr'), run(g.gen_instr))
		
		entry = instr | label_def

		progr = List(entry).setParseAction(run(self.gen_end_progr))
		
		return progr
开发者ID:institution,项目名称:tri,代码行数:32,代码来源:asm.py

示例4: parse_upstreams

# 需要导入模块: from pyparsing import Word [as 别名]
# 或者: from pyparsing.Word import copy [as 别名]
    def parse_upstreams(self):
        # function to create range validation parse actions
        def validInRange(lo, hi):
            def parseAction(tokens):
                if not lo <= int(tokens[0]) <= hi:
                    raise ParseException("", 0, "integer outside range %d-%d" % (lo, hi))

            return parseAction

        # define basic building blocks
        integer = Word(nums)
        ip_int = integer.copy().setParseAction(validInRange(0, 255))
        ip_addr = Combine(ip_int + ("." + ip_int) * 3)
        ip_port = integer.copy().setParseAction(validInRange(1025, 65535))
        ip_addr_port = ip_addr("ip_addr") + ":" + ip_port("ip_port")
        ident = Word(alphas, alphanums + "_")

        # define punctuation needed — but use Suppress so it does
        # not clutter up the output tokens
        SEMI, LBRACE, RBRACE = map(Suppress, ";{}")

        # define a server entry that will be found in each upstream block
        server_def = Keyword("server") + ip_addr_port + SEMI

        # define an upstream block
        upstream_block = (
            Keyword("upstream") + ident("stream_id") + LBRACE + OneOrMore(Group(server_def))("servers") + RBRACE
        )

        # now scan through the string containing the nginx config
        # data, extract the upstream blocks and their corresponding
        # server definitions — access tokens using results names as
        # specified when defining server_def and upstream_block
        for usb in upstream_block.searchString(self.nginx_config):
            upstream = []
            for server in usb.servers:
                upstream.append(server.ip_addr + ":" + server.ip_port)
            self.upstreams[usb.stream_id] = upstream
开发者ID:Strayer,项目名称:dev-services-launcher,代码行数:40,代码来源:Nginx.py

示例5: init_grammar

# 需要导入模块: from pyparsing import Word [as 别名]
# 或者: from pyparsing.Word import copy [as 别名]
    def init_grammar(self):
        """Set up the parsing classes
        Any changes to the grammar of the config file be done here.
        """

        # Some syntax that we need, but don't care about
        SEMICOLON = (Suppress(";"))
        EQUALS = Suppress("=")

        # Top Section
        FILE_NAME = Word(alphas + nums + '-_.')
        alignment_def = Keyword('alignment') + EQUALS\
                        + FILE_NAME + SEMICOLON
        alignment_def.setParseAction(self.set_alignment)

        tree_def = Keyword('user_tree_topology') + EQUALS\
                   + FILE_NAME + SEMICOLON
        tree_def.setParseAction(self.set_user_tree)

        def simple_option(name):
            opt = Keyword(name) + EQUALS +\
                  Word(alphas + nums + '-_') + SEMICOLON
            opt.setParseAction(self.set_simple_option)
            return opt

        branch_def = simple_option('branchlengths')

        MODEL_NAME = Word(alphas + nums + '+' + ' ' + '_')
        model_list = delimitedList(MODEL_NAME)
        model_def = 'models' + EQUALS + model_list + SEMICOLON
        model_def.setParseAction(self.set_models)

        model_selection_def = simple_option("model_selection")
        top_section = alignment_def + Optional(tree_def) + branch_def + \
            model_def + model_selection_def


        # Data Block Parsing
        column = Word(nums)
        block_name = Word(alphas + '_-' + nums)
        block_def = column("start") +\
            Optional(Suppress("-") + column("end")) +\
            Optional(Suppress("\\") + column("step"))
        block_def.setParseAction(self.define_range)

        block_list_def = Group(OneOrMore(Group(block_def)))

        user_subset_def = Optional("charset") + block_name("name") + \
            EQUALS + block_list_def("parts") + SEMICOLON
        user_subset_def.setParseAction(self.define_user_subset)

        block_def_list = OneOrMore(Group(user_subset_def))
        block_section = Suppress("[data_blocks]") + block_def_list
        block_def_list.setParseAction(self.check_blocks)

        # Scheme Parsing
        scheme_name = Word(alphas + '_-' + nums)

        # Make a copy, cos we set a different action on it
        user_subset_ref = block_name.copy()
        user_subset_ref.setParseAction(self.check_block_exists)

        subset = Group(Suppress("(") +
                       delimitedList(user_subset_ref("name")) + Suppress(")"))
        subset.setParseAction(self.define_subset_grouping)

        scheme = Group(OneOrMore(subset))
        scheme_def = scheme_name("name") + \
            EQUALS + scheme("scheme") + SEMICOLON
        scheme_def.setParseAction(self.define_scheme)

        scheme_list = OneOrMore(Group(scheme_def))

        scheme_algo = simple_option("search")
        scheme_section = \
            Suppress("[schemes]") + scheme_algo + Optional(scheme_list)

        # We've defined the grammar for each section.
        # Here we just put it all together
        self.config_parser = (
            top_section + block_section + scheme_section + stringEnd)
开发者ID:marekborowiec,项目名称:partitionfinder,代码行数:83,代码来源:parser.py

示例6: oneOf

# 需要导入模块: from pyparsing import Word [as 别名]
# 或者: from pyparsing.Word import copy [as 别名]
binop = oneOf(binopstr)
arithSign = Word("+-", exact=1)

realNum = Combine(Optional(arithSign) +
                  (Word(nums) + "." + Optional(Word(nums)) | ("." + Word(nums)))  # noqa
                  + Optional(E + Optional(arithSign) + Word(nums)))
realNum.setParseAction(lambda x: expression.NumericLiteral(float(x[0])))

intNum = Combine(Optional(arithSign) + Word(nums) +
                 Optional(E + Optional("+") + Word(nums)))
intNum.setParseAction(lambda x: expression.NumericLiteral(int(x[0])))

number = realNum | intNum

variable = ident.copy()
variable.setParseAction(lambda x: model.Var(x[0]))

quotedString.setParseAction(lambda x: expression.StringLiteral(x[0][1:-1]))

literal = quotedString | number

valueref = variable | literal


def mkterm(x):
    return model.Term(x)

term = (predicate
        + drop("(")
        + Group(delimitedList(valueref, ","))
开发者ID:EvgenyKarataev,项目名称:raco,代码行数:32,代码来源:grammar.py

示例7: SPICE_BNF

# 需要导入模块: from pyparsing import Word [as 别名]
# 或者: from pyparsing.Word import copy [as 别名]
def SPICE_BNF():
    global bnf

    if not bnf:

        # punctuation
        colon = Literal(":").suppress()
        lbrace = Literal("{").suppress()
        rbrace = Literal("}").suppress()
        lbrack = Literal("[").suppress()
        rbrack = Literal("]").suppress()
        lparen = Literal("(").suppress()
        rparen = Literal(")").suppress()
        equals = Literal("=").suppress()
        comma = Literal(",").suppress()
        semi = Literal(";").suppress()

        # primitive types
        int8_ = Keyword("int8").setParseAction(replaceWith(ptypes.int8))
        uint8_ = Keyword("uint8").setParseAction(replaceWith(ptypes.uint8))
        int16_ = Keyword("int16").setParseAction(replaceWith(ptypes.int16))
        uint16_ = Keyword("uint16").setParseAction(replaceWith(ptypes.uint16))
        int32_ = Keyword("int32").setParseAction(replaceWith(ptypes.int32))
        uint32_ = Keyword("uint32").setParseAction(replaceWith(ptypes.uint32))
        int64_ = Keyword("int64").setParseAction(replaceWith(ptypes.int64))
        uint64_ = Keyword("uint64").setParseAction(replaceWith(ptypes.uint64))

        # keywords
        enum32_ = Keyword("enum32").setParseAction(replaceWith(32))
        enum16_ = Keyword("enum16").setParseAction(replaceWith(16))
        enum8_ = Keyword("enum8").setParseAction(replaceWith(8))
        flags32_ = Keyword("flags32").setParseAction(replaceWith(32))
        flags16_ = Keyword("flags16").setParseAction(replaceWith(16))
        flags8_ = Keyword("flags8").setParseAction(replaceWith(8))
        channel_ = Keyword("channel")
        server_ = Keyword("server")
        client_ = Keyword("client")
        protocol_ = Keyword("protocol")
        typedef_ = Keyword("typedef")
        struct_ = Keyword("struct")
        message_ = Keyword("message")
        image_size_ = Keyword("image_size")
        bytes_ = Keyword("bytes")
        cstring_ = Keyword("cstring")
        switch_ = Keyword("switch")
        default_ = Keyword("default")
        case_ = Keyword("case")

        identifier = Word(alphas, alphanums + "_")
        enumname = Word(alphanums + "_")

        integer = (
            (Combine(CaselessLiteral("0x") + Word(nums + "abcdefABCDEF")) | Word(nums + "+-", nums))
            .setName("int")
            .setParseAction(cvtInt)
        )

        typename = identifier.copy().setParseAction(lambda toks: ptypes.TypeRef(str(toks[0])))

        # This is just normal "types", i.e. not channels or messages
        typeSpec = Forward()

        attributeValue = integer ^ identifier
        attribute = Group(Combine("@" + identifier) + Optional(lparen + delimitedList(attributeValue) + rparen))
        attributes = Group(ZeroOrMore(attribute))
        arraySizeSpecImage = Group(image_size_ + lparen + integer + comma + identifier + comma + identifier + rparen)
        arraySizeSpecBytes = Group(bytes_ + lparen + identifier + comma + identifier + rparen)
        arraySizeSpecCString = Group(cstring_ + lparen + rparen)
        arraySizeSpec = (
            lbrack
            + Optional(
                identifier ^ integer ^ arraySizeSpecImage ^ arraySizeSpecBytes ^ arraySizeSpecCString, default=""
            )
            + rbrack
        )
        variableDef = Group(
            typeSpec
            + Optional("*", default=None)
            + identifier
            + Optional(arraySizeSpec, default=None)
            + attributes
            - semi
        ).setParseAction(parseVariableDef)

        switchCase = Group(
            Group(
                OneOrMore(
                    default_.setParseAction(replaceWith(None)) + colon
                    | Group(case_.suppress() + Optional("!", default="") + identifier) + colon
                )
            )
            + variableDef
        ).setParseAction(lambda toks: ptypes.SwitchCase(toks[0][0], toks[0][1]))
        switchBody = Group(
            switch_
            + lparen
            + delimitedList(identifier, delim=".", combine=True)
            + rparen
            + lbrace
            + Group(OneOrMore(switchCase))
#.........这里部分代码省略.........
开发者ID:Truefans,项目名称:spice-protocol,代码行数:103,代码来源:spice_parser.py

示例8: range

# 需要导入模块: from pyparsing import Word [as 别名]
# 或者: from pyparsing.Word import copy [as 别名]
        (False, False) : "value %%s is not in the range (%s to %s)" % (minval,maxval),
        }[minval is None, maxval is None]

    # define the actual range checking parse action
    def rangeCheckParseAction(string, loc, tokens):
        parsedval = tokens[0]
        if not inRangeFn(parsedval):
            raise ParseException(string, loc, outOfRangeMessage % parsedval)

    return rangeCheckParseAction

# define the expressions for a date of the form YYYY/MM/DD or YYYY/MM (assumes YYYY/MM/01)
integer = Word(nums).setName("integer")
integer.setParseAction(lambda t:int(t[0]))

month = integer.copy().addParseAction(rangeCheck(1,12))
day = integer.copy().addParseAction(rangeCheck(1,31))
year = integer.copy().addParseAction(rangeCheck(2000, None))

SLASH = Suppress('/')
dateExpr = year("year") + SLASH + month("month") + Optional(SLASH + day("day"))
dateExpr.setName("date")

# convert date fields to datetime (also validates dates as truly valid dates)
dateExpr.setParseAction(lambda t: datetime(t.year, t.month, t.day or 1).date())

# add range checking on dates
mindate = datetime(2002,1,1).date()
maxdate = datetime.now().date()
dateExpr.addParseAction(rangeCheck(mindate, maxdate))
开发者ID:0x0mar,项目名称:phpsploit,代码行数:32,代码来源:rangeCheck.py

示例9: Literal

# 需要导入模块: from pyparsing import Word [as 别名]
# 或者: from pyparsing.Word import copy [as 别名]
name_eq = Literal('name') + '=' + quotedString
bind_keyword = Keyword('bind').setParseAction(lambda s,loc,toks: [' bind'])
bind_attr = bind_keyword + Literal('(') + 'c' + Optional(comma + name_eq) + ')'
result_attr = Literal('result') + '(' + NAME + ')'
result_attr.setParseAction(lambda s,loc,toks: [' '+''.join(toks)])
func_post = eachMostOnce(bind_attr, result_attr)

elem_attr = Keyword('elemental').setName('elemental')
elem_attr.setParseAction(lambda s,loc,toks: [toks[0] + ' '])
pure_attr = Keyword('pure').setName('pure')
pure_attr.setParseAction(lambda s,loc,toks: [toks[0] + ' '])
recu_attr = Keyword('recursive').setName('elemental')
recu_attr.setParseAction(lambda s,loc,toks: [toks[0] + ' '])
func_pre  = eachMostOnce(elem_attr, pure_attr, recu_attr)

func_name = NAME.copy().setName('func_name')
func_name.setParseAction(lambda s,loc,toks: [' '+toks[0]])


func_def = Optional(func_pre) + Keyword('function') + func_name + arglist \
        + Optional(func_post) + EOLL
func_def.setParseAction(lambda s,loc,toks: [''.join(toks), '', 'end function'])

subr_def = Keyword('subroutine') + func_name + arglist + Optional(bind_attr) + EOLL
subr_def.setParseAction(lambda s,loc,toks: [''.join(toks), '', 'end subroutine'])

inte_name = NAME.copy().setParseAction(lambda s,loc,toks: [' '+toks[0]])
inte_assignment = Literal('assignment') + '(' + Literal('=') + ')'
inte_assignment.setParseAction(lambda s,loc,toks: [' ' + ''.join(toks)])
operators = comp_op | oneOf('+ - * / ** //') | Combine('.' + NAME + '.')
inte_operator = Literal('operator') + '(' + operators + ')'
开发者ID:fermat618,项目名称:fortran-construct-complete,代码行数:33,代码来源:fortran_construct_complete.py

示例10: Optional

# 需要导入模块: from pyparsing import Word [as 别名]
# 或者: from pyparsing.Word import copy [as 别名]
              
conditionals << Optional(not_logic) + conditional + ZeroOrMore(binary_logic + conditional)

if_keyword = Literal('if')

if_statement = (if_keyword + conditionals).setParseAction(IfStatement)

option = Forward()

response_definition = text + lineEnd.suppress() + Optional(if_statement + Literal('then').suppress())
response = (response_definition + ZeroOrMore(indentedBlock(option, indentStack, True))).setParseAction(Response)

event_send = Literal('->')
event_message_separator = Literal('!').suppress()

event_atom = atom.copy().setParseAction(lambda t: repr(t[0]))
event_message = quotedString | event_atom
event_send_separator = Literal(',').suppress()
event_statement = (event_send + event_atom + event_message_separator + event_message).setParseAction(Event)

options_delimiter =  Literal('~')
options_definition = options_delimiter + text + Optional(event_statement + ZeroOrMore(event_send_separator + event_statement))

option << (options_definition + ZeroOrMore(indentedBlock(response, indentStack, True))).setParseAction(Option)

dialog_begin = Literal('begin').suppress() + Group(atom + Optional(Literal('extends').suppress() + atom))
dialog_end = Literal('end').suppress()
dialog = (dialog_begin + ZeroOrMore(indentedBlock(response, indentStack, True)) + dialog_end).setParseAction(Dialog)

dialogs = ZeroOrMore(indentedBlock(dialog, indentStack, False))
开发者ID:saebyn,项目名称:diac,代码行数:32,代码来源:parser.py

示例11: init_grammar

# 需要导入模块: from pyparsing import Word [as 别名]
# 或者: from pyparsing.Word import copy [as 别名]
    def init_grammar(self):
        """Set up the parsing classes
        Any changes to the grammar of the config file be done here.
        """
        # Some syntax that we need, but don't bother looking at
        SEMICOLON = (Suppress(";"))
        EQUALS = Suppress("=")
        OPENB = Suppress("(")
        CLOSEB = Suppress(")")
        BACKSLASH = Suppress("\\")
        DASH = Suppress("-")

        # Top Section
        FILENAME = Word(alphas + nums + '-_.')
        alignmentdef = Keyword('alignment') + EQUALS + FILENAME + SEMICOLON
        alignmentdef.setParseAction(self.set_alignment)

        treedef = Keyword('user_tree_topology') + EQUALS + FILENAME + SEMICOLON
        treedef.setParseAction(self.set_user_tree)

        def simple_option(name):
            opt = Keyword(name) + EQUALS + Word(alphas + nums + '-_') + SEMICOLON
            opt.setParseAction(self.set_simple_option)
            return opt

        branchdef = simple_option('branchlengths')

        MODELNAME = Word(alphas + nums + '+')
        modellist = delimitedList(MODELNAME)
        modeldef = Keyword("models") + EQUALS + Group(
            (
                CaselessKeyword("all") | CaselessKeyword("mrbayes") | CaselessKeyword("raxml") |
                CaselessKeyword("beast") | CaselessKeyword("all_protein") |
                CaselessKeyword(
                    "all_protein_gamma") | CaselessKeyword("all_protein_gammaI")
            )("predefined") |
            Group(modellist)("userlist")) + SEMICOLON
        modeldef.setParseAction(self.set_models)

        modseldef = simple_option("model_selection")
        topsection = alignmentdef + Optional(treedef) + branchdef + \
            modeldef + modseldef

        # Partition Parsing
        column = Word(nums)
        partname = Word(alphas + '_-' + nums)
        partdef = column("start") +\
            Optional(DASH + column("end")) +\
            Optional(BACKSLASH + column("step"))

        partdef.setParseAction(self.define_range)
        partdeflist = Group(OneOrMore(Group(partdef)))
        partition = Optional("charset") + partname("name") + \
            EQUALS + partdeflist("parts") + SEMICOLON
        partition.setParseAction(self.define_partition)
        partlist = OneOrMore(Group(partition))
        partsection = Suppress("[data_blocks]") + partlist

        # Scheme Parsing
        schemename = Word(alphas + '_-' + nums)
        partnameref = partname.copy(
        )  # Make a copy, cos we set a different action on it
        partnameref.setParseAction(self.check_part_exists)

        subset = Group(OPENB + delimitedList(partnameref("name")) + CLOSEB)
        subset.setParseAction(self.define_subset)

        scheme = Group(OneOrMore(subset))
        schemedef = schemename("name") + \
            EQUALS + scheme("scheme") + SEMICOLON
        schemedef.setParseAction(self.define_schema)

        schemelist = OneOrMore(Group(schemedef))

        schemealgo = simple_option("search")
        schemesection = \
            Suppress("[schemes]") + schemealgo + Optional(schemelist)

        # We've defined the grammar for each section. Here we just put it all together
        self.config_parser = (
            topsection + partsection + schemesection + stringEnd)
开发者ID:LaureneAlicia,项目名称:partitionfinder,代码行数:83,代码来源:parser.py

示例12: __init__

# 需要导入模块: from pyparsing import Word [as 别名]
# 或者: from pyparsing.Word import copy [as 别名]
    def __init__(self):
        # define SQL tokens
        selectStmt = Forward()
        selectToken = Keyword("select", caseless=True)
        fromToken   = Keyword("from", caseless=True)
        asToken   = Keyword("as", caseless=True)
        whereToken = Keyword("where", caseless=True)
        semicolon = Literal(";")

        ident = Word( alphas, alphanums + "_$" ).setName("identifier")

        columnName     = delimitedList( ident, ".", combine=True )
        #columnName.setParseAction(upcaseTokens)
        columnNameList = Group( columnName + ZeroOrMore("," + columnName))
#        selectableList = Forward()
        columnRvalList = Forward()
        functionExpr = ident + Optional("."+ident) + Literal('(') + columnRvalList + Literal(')')
        alias = Forward()
        identExpr  = functionExpr | ident
        self.identExpr = identExpr # Debug
        self.functionExpr = functionExpr # Debug
        alias = ident.copy()

        selectableName = identExpr | columnName

        selectableList = Group( selectableName + ZeroOrMore(","+selectableName))
        columnRef = columnName
        functionSpec = functionExpr
        valueExprPrimary = functionSpec | columnRef
        numPrimary = valueExprPrimary ## | numericValFunc
        factor = Optional(Literal("+") | Literal("-")) + numPrimary
        muldiv = oneOf("* /")
        term = Forward()
        term << factor + Optional(muldiv + factor)
        numericExpr = Forward()
        addsub = oneOf("+ -")
        numericExpr << term + Optional(addsub + numericExpr)

        arithop = oneOf("+ - * /")
        columnNumericExpr = Forward()
        cTerm = valueExprPrimary
        testme = valueExprPrimary + arithop + valueExprPrimary
        columnNumericExpr << cTerm + Optional(arithop + columnNumericExpr)
        colNumExpList = Group( columnNumericExpr + ZeroOrMore(","+columnNumericExpr)) 
        

        valueExpr = numericExpr ## | stringExpr | dateExpr | intervalExpr
        derivedColumn = valueExpr + Optional(asToken + alias)
        selectSubList = derivedColumn + ZeroOrMore("," + derivedColumn)


        tableName      = delimitedList( ident, ".", combine=True )
        # don't upcase table names anymore
        # tableName.setParseAction(upcaseTokens) 
        self.tableAction = []
        tableName.addParseAction(self.actionWrapper(self.tableAction))
        tableName.setResultsName("table")
        tableAlias = tableName + asToken + ident.setResultsName("aliasName")
        tableAlias.setResultsName("alias")
        genericTableName = tableAlias | tableName
        genericTableName = genericTableName.setResultsName("tablename")
        tableNameList  = Group( genericTableName 
                                + ZeroOrMore("," + genericTableName))

        whereExpression = Forward()
        and_ = Keyword("and", caseless=True)
        or_ = Keyword("or", caseless=True)
        in_ = Keyword("in", caseless=True)
        between_ = Keyword("between", caseless=True)
    
        E = CaselessLiteral("E")
        binop = oneOf("= != < > >= <= eq ne lt le gt ge", caseless=True)
        arithSign = Word("+-",exact=1)
        realNum = Combine( Optional(arithSign) + ( Word( nums ) + "." 
                                                   + Optional( Word(nums) )  |
                                                   ( "." + Word(nums) ) ) + 
                           Optional( E + Optional(arithSign) + Word(nums) ) )
        intNum = Combine( Optional(arithSign) + Word( nums ) + 
                          Optional( E + Optional("+") + Word(nums) ) )

        # need to add support for alg expressions
        columnRval = realNum | intNum | quotedString | columnNumericExpr# | numericExpr 
        columnRvalList << Group( columnRval + ZeroOrMore("," + columnRval))

        self.whereExpAction = []

        namedRv = columnRval.setResultsName("column")
        whereConditionFlat = Group(
            ( functionSpec + binop + columnRval) |
            ( namedRv + binop + columnRval ) |
            ( namedRv + in_ + "(" + columnRval + ZeroOrMore(","+namedRv) + ")" ) |
            ( namedRv + in_ + "(" + selectStmt + ")" ) |
            ( namedRv + between_ + namedRv + and_ + namedRv ) )

        whereConditionFlat.addParseAction(self.actionWrapper(self.whereExpAction))
        whereCondition = Group(whereConditionFlat 
                               | ( "(" + whereExpression + ")" ))

        # Test code to try to make an expression parse.
        # print whereConditionFlat.parseString("ABS(o1.ra - o2.ra) < 0.00083 / COS(RADIANS(o2.decl))")
#.........这里部分代码省略.........
开发者ID:lsst-dm,项目名称:legacy-qserv_master,代码行数:103,代码来源:sqlparser.py

示例13: __init__

# 需要导入模块: from pyparsing import Word [as 别名]
# 或者: from pyparsing.Word import copy [as 别名]
class Parsers:
    def __init__(self, debug=False):
        self._debug = debug
        self._create_whitespace_parser()
        self._create_field_parser()
        self._create_ip_address_parser()
        self._create_canonical_hostname_parser()
        self._create_alias_parser()
        self._create_aliases_parser()
        self._create_entry_parser()
        self._create_comment_parser()
        self._create_line_content()
        self._create_line_end_parser()
        self._create_line_parser()
        self._create_hosts_parser()

    def _config(self, parser, name, parse_action):
        parser.leaveWhitespace()
        parser.setDebug(self._debug)
        parser.setName(name)
        parser.setParseAction(parse_action)

    def _create_alias_parser(self):
        def parse_action(string, location, tokens):
            return AliasNode(tokens[0])
        self.alias = self.field.copy()
        self._config(self.alias, 'alias', parse_action)

    def _create_aliases_parser(self):
        def parse_action(string, location, tokens):
            return AliasesNode(tokens.asList())
        self.aliases = self.alias + ZeroOrMore(self.whitespace + self.alias)
        self._config(self.aliases, 'aliases', parse_action)

    def _create_entry_parser(self):
        def parse_action(string, location, tokens):
            return EntryNode(tokens.asList())
        self.entry = (
            self.ip_address +
            self.whitespace +
            self.canonical_hostname +
            Optional(self.whitespace + self.aliases)
        )
        self._config(self.entry, 'entry', parse_action)

    def _create_field_parser(self):
        self.field = Word(printables.replace(COMMENT_START, ''))
        self._config(self.field, 'field', lambda: None)

    def _create_canonical_hostname_parser(self):
        def parse_action(string, location, tokens):
            return CanonicalHostnameNode(tokens[0])
        self.canonical_hostname = self.field.copy()
        self._config(self.canonical_hostname, 'canonical_hostname',
                     parse_action)

    def _create_comment_parser(self):
        def parse_action(string, location, tokens):
            return CommentNode(''.join(tokens.asList()))
        self.comment = COMMENT_START + restOfLine
        self._config(self.comment, 'comment', parse_action)

    def _create_ip_address_parser(self):
        def parse_action(string, location, tokens):
            return IPAddressNode(tokens[0])
        self.ip_address = self.field.copy()
        self._config(self.ip_address, 'ip_address', parse_action)

    def _create_hosts_parser(self):
        def parse_action(string, location, tokens):
            return HostsNode(tokens.asList())
        self.hosts = ZeroOrMore(self.line) + StringEnd()
        self._config(self.hosts, 'hosts', parse_action)

    def _create_line_content(self):
        def parse_action(string, location, tokens):
            return LineContentNode(tokens.asList())
        self.line_content = (Optional(self.whitespace) + Optional(self.entry) +
                             Optional(self.whitespace) +
                             Optional(self.comment))
        self._config(self.line_content, 'line_content', parse_action)

    def _create_line_parser(self):
        def parse_action(string, location, tokens):
            return LineNode(tokens.asList())
        self.line = self.line_content + self.line_end
        self._config(self.line, 'line', parse_action)

    def _create_line_end_parser(self):
        def parse_action(string, location, tokens):
            return LineEndNode(tokens[0])
        self.line_end = LineEnd()
        self._config(self.line_end, 'line_end', parse_action)

    def _create_whitespace_parser(self):
        def parse_action(string, location, tokens):
            return WhitespaceNode(tokens[0])
        self.whitespace = Word('\t ')
        self._config(self.whitespace, 'white_space', parse_action)
开发者ID:foxdog-studios,项目名称:hosts,代码行数:101,代码来源:parser.py


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