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

Python pyparsing.OneOrMore类代码示例

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

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



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

示例1: order_cluster_by_load

  def order_cluster_by_load(self, cluster_list):
    # Sample salt output
    # {'dlceph01.drwg.local': '0.27 0.16 0.15 1/1200 26234'}

    # define grammar
    point = Literal('.')
    number = Word(nums) 
    floatnumber = Combine( number + point + number)
    float_list = OneOrMore(floatnumber)

    results = self.salt_client.cmd(','.join(cluster_list), 'cmd.run', ['cat /proc/loadavg'], expr_form='list')
    load_list = []
    self.logger.debug("Salt load return: {load}".format(load=results))

    for host in results:
      host_load = results[host]
      match = float_list.parseString(host_load)
      if match:
        one_min = match[0]
        five_min = match[1]
        fifteen_min = match[2]
        self.logger.debug("Adding Load({host}, {one_min}, {five_min}, {fifteen_min}".format(
          host=host, one_min=one_min, five_min=five_min, fifteen_min=fifteen_min))
        load_list.append(Load(host, one_min, five_min, fifteen_min))
      else:
        self.logger.error("Could not parse host load output")

    # Sort the list by fifteen min load
    load_list = sorted(load_list, key=lambda x: x.fifteen_min_load)
    for load in load_list:
      self.logger.debug("Sorted load list: " + str(load))

    return load_list
开发者ID:Empia,项目名称:autodock,代码行数:33,代码来源:manager.py


示例2: main

def main(index,line):
  
          
   # Do something with this data.
   if line is not None:
      try:
	
	operator = Regex(r'(?<![\+\-\^\*/%])[\+\-]|[\^\*/%!]')
	function = Regex(r'[a-zA-Z_][a-zA-Z0-9_]*(?=([ \t]+)?\()')
	variable = Regex(r'[+-]?[a-zA-Z_][a-zA-Z0-9_]*(?!([ \t]+)?\()')
	number = Regex(r'[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?')
	lbrace = Word('(')
	rbrace = Word(')')
	assign = Literal(':=')
	linebreak = Word('\n')
	skip = Word(' \t')
           
	lexOnly = operator | function | variable | number | lbrace \
            | rbrace | assign | linebreak | skip
	
        lexAllOnly = OneOrMore(lexOnly)
         
        print lexAllOnly.parseString(line)
        print '\n------------------------------\n'
      except ParseException, err:
         print err.line
         print " "*(err.column-1) + "^"
         print "Error en la linea, {index}, columna: {e.col} elemento no identificado".format(e=err,index=index)
         print '\n------------------------------\n'
开发者ID:miguelalexanderdiaz,项目名称:lenguajes_project,代码行数:29,代码来源:analizador_lexico.py


示例3: parse_string

    def parse_string(self, string):
        '''Populate a new object from a string.
        
        Parsing is hard, so we're going to call out to the pyparsing
        library here.  I hope you installed it!
        FTR: this is hideous.
        '''
        from pyparsing import Suppress, Regex, quotedString, restOfLine, Keyword, nestedExpr, Group, OneOrMore, Word, Literal, alphanums, removeQuotes, replaceWith, nums, printables
        gr_eq = Literal('=')
        gr_stripped_string = quotedString.copy().setParseAction( removeQuotes )
        gr_opt_quoted_string = gr_stripped_string | restOfLine
        gr_number = Word(nums)
        gr_yn = Keyword('yes', caseless=True).setParseAction(replaceWith('1')) | Keyword('no', caseless=True).setParseAction(replaceWith('0'))

        def _handle_ip(*x):
            a,b,c =  x[2]
            return '  %s = { %s }' % (a,c[0])

        def _handle_diraddr(*x):
            a,b,c =  x[2]
            self._set(DIRADDRESSES, '  %s' % '\n  '.join(c))
            return

        def np(words, fn = gr_opt_quoted_string, action=None):
            p = Keyword(words[0], caseless=True)
            for w in words[1:]:
                p = p | Keyword(w, caseless=True)
            p = p + gr_eq + fn
            p.setParseAction(action)
            return p
            
        gr_name = np((NAME,), action=lambda x: self._set_name(x[2]))
        gr_address = np((ADDRESS,), action=self._parse_setter(ADDRESS))
        gr_fd_conn = np(PList('fd connect timeout'), gr_number, self._parse_setter(FD_CONNECT_TIMEOUT, True))
        gr_heart = np(PList('heartbeat interval'), gr_number, self._parse_setter(HEARTBEATINTERVAL, True))
        gr_max_con = np(PList('maximum console connections'),
                        gr_number, self._parse_setter(MAXIMUMCONSOLECONNECTIONS, True))
        gr_max_jobs = np(PList('maximum concurrent jobs'), gr_number, action=self._parse_setter(MAXIMUMCONCURRENTJOBS, True))
        gr_pass = np((PASSWORD,), action=self._parse_setter(PASSWORD))
        gr_pid = np(PList('pid directory'), action=self._parse_setter(PIDDIRECTORY))
        gr_query = np(PList('query file'), action=self._parse_setter(QUERYFILE))
        gr_scripts = np(PList('scripts directory'), action=self._parse_setter(SCRIPTS_DIRECTORY))
        gr_sd_conn = np(PList('sd connect timeout'), gr_number, self._parse_setter(SD_CONNECT_TIMEOUT, True))
        gr_source = np(PList('source address'), action=self._parse_setter(SOURCEADDRESS))
        gr_stats = np(PList('statistics retention'), action=self._parse_setter(STATISTICS_RETENTION))
        gr_verid = np((VERID,), action=self._parse_setter(VERID))
        gr_messages = np((MESSAGES,), action=lambda x:self._parse_setter(MESSAGE_ID, dereference=True))
        gr_work_dir = np(PList('working directory'), action=self._parse_setter(WORKINGDIRECTORY))
        gr_port = np(PList('dir port'), gr_number, self._parse_setter(PORT, True))
        gr_monitor = np((MONITOR,), gr_yn, action=self._parse_setter(MONITOR))

        # This is a complicated one
        da_addr = np(('Addr','Port'), Word(printables), lambda x,y,z: ' '.join(z))
        da_ip = np(('IPv4','IPv6','IP'), nestedExpr('{','}', OneOrMore(da_addr).setParseAction(lambda x,y,z: ' ; '.join(z)))).setParseAction(_handle_ip)
        da_addresses = np(PList('dir addresses'), nestedExpr('{','}', OneOrMore(da_ip)), _handle_diraddr)

        gr_res = OneOrMore(gr_name | gr_address | gr_fd_conn | gr_heart | gr_max_con | gr_max_jobs | gr_pass | gr_pid | gr_query | gr_scripts | gr_sd_conn | gr_source | gr_stats | gr_verid | gr_messages | gr_work_dir | gr_port | gr_monitor | da_addresses)

        result = gr_res.parseString(string, parseAll=True)
        return 'Director: ' + self[NAME]
开发者ID:amon-ra,项目名称:bacula_configuration,代码行数:60,代码来源:director.py


示例4: make_grammar

def make_grammar():
    """Creates the grammar to be used by a spec matcher."""
    # This is apparently how pyparsing recommends to be used,
    # as http://pyparsing.wikispaces.com/share/view/644825 states that
    # it is not thread-safe to use a parser across threads.

    unary_ops = (
        # Order matters here (so that '=' doesn't match before '==')
        Literal("==") | Literal("=") |
        Literal("!=") | Literal("<in>") |
        Literal(">=") | Literal("<=") |
        Literal("s==") | Literal("s!=") |
        # Order matters here (so that '<' doesn't match before '<=')
        Literal("s<=") | Literal("s<") |
        # Order matters here (so that '>' doesn't match before '>=')
        Literal("s>=") | Literal("s>"))

    or_ = Literal("<or>")

    # An atom is anything not an keyword followed by anything but whitespace
    atom = ~(unary_ops | or_) + Regex(r"\S+")

    unary = unary_ops + atom
    disjunction = OneOrMore(or_ + atom)

    # Even-numbered tokens will be '<or>', so we drop them
    disjunction.setParseAction(lambda _s, _l, t: ["<or>"] + t[1::2])

    expr = disjunction | unary | atom
    return expr
开发者ID:singh264,项目名称:ugradproject,代码行数:30,代码来源:specs_matcher.py


示例5: pyparsing_parse

def pyparsing_parse(text):
    WHITESPACE = re.compile(r"\s+")
    books = {}
    key_values = {}

    def normalize(tokens):
        return WHITESPACE.sub(" ", tokens[0])

    def add_key_value(tokens):
        key_values[tokens.key] = tokens.value

    def add_book(tokens):
        books[tokens.identifier] = key_values.copy()
        key_values.clear()

    left_brace, right_brace, comma, equals = map(Suppress, "{},=")
    start = Suppress("@Book") + left_brace
    identifier = Regex(r"[a-zA-Z][^,\s]*")("identifier") + comma
    key = Word(alphas, alphanums)("key")
    value = (Word(nums).setParseAction(lambda t: int(t[0])) |
             QuotedString('"', multiline=True).setParseAction(normalize)
            )("value")
    key_value = (key + equals + value).setParseAction(add_key_value)
    end = right_brace
    bibtex = (start + identifier + delimitedList(key_value) + end
             ).setParseAction(add_book)
    parser = OneOrMore(bibtex)
    try:
        parser.parseString(text)
    except ParseException as err:
        print("parse error: {0}".format(err))
    return books
开发者ID:178220709,项目名称:PyHello,代码行数:32,代码来源:BibTeX.py


示例6: parse_ampersand_comment

def parse_ampersand_comment(s):
    import pyparsing
    pyparsing.ParserElement.enablePackrat()
    from pyparsing import Word, Literal, QuotedString, CaselessKeyword, \
         OneOrMore, Group, Optional, Suppress, Regex, Dict
    word = Word(string.letters+string.digits+"%_")
    key = word.setResultsName("key") + Suppress("=")
    single_value = (Word(string.letters+string.digits+"-.") |
                    QuotedString("'") |
                    QuotedString('"'))
    range_value = Group(Suppress("{") +
                        single_value.setResultsName("min") +
                        Suppress(",") +
                        single_value.setResultsName("max") +
                        Suppress("}"))
    pair = (key + (single_value | range_value).setResultsName("value"))
    g = OneOrMore(pair)
    d = []
    for x in g.searchString(s):
        v = x.value
        if type(v) == str:
            try: v = float(v)
            except ValueError: pass
        else:
            try: v = map(float, v.asList())
            except ValueError: pass
        d.append((x.key, v))
    return d
开发者ID:ChriZiegler,项目名称:cython-experiments-1,代码行数:28,代码来源:newick.py


示例7: init_parser

    def init_parser(self):

        INTEGER = Word(nums)
        INTEGER.setParseAction(lambda x: int(x[0]))

        header = INTEGER("species_count") + INTEGER("sequence_length") +\
            Suppress(restOfLine)
        header.setParseAction(self.set_header)

        sequence_name = Word(
            alphas + nums + "!#$%&\'*+-./;<=>[email protected][\\]^_`{|}~",
            max=100)

        # Take a copy and disallow line breaks in the bases
        bases = self.BASES.copy()
        bases.setWhitespaceChars(" \t")
        seq_start = sequence_name("species") + bases(
            "sequence") + Suppress(LineEnd())
        seq_start.setParseAction(self.set_seq_start)
        seq_start_block = OneOrMore(seq_start)
        seq_start_block.setParseAction(self.set_start_block)

        seq_continue = bases("sequence") + Suppress(LineEnd())
        seq_continue.setParseAction(self.set_seq_continue)

        seq_continue_block = Suppress(LineEnd()) + OneOrMore(seq_continue)
        seq_continue_block.setParseAction(self.set_continue_block)

        return header + seq_start_block + ZeroOrMore(seq_continue_block)
开发者ID:brettc,项目名称:tigger,代码行数:29,代码来源:alignment.py


示例8: ifParser

def ifParser():
	
	comma = Literal(",").suppress()
	hash = Literal("#").suppress()
	equal = Literal("=").suppress()

	# Rules and labels
	rulename = Word (alphanums + "_")
	rulecategory = oneOf("Protocol_Rules Invariant_Rules Decomposition_Rules Intruder_Rules Init Goal")
	label = hash + Literal("lb") + equal + rulename + comma + Literal("type") + equal + rulecategory
	labeledrule = Group(label) + Group(ruleParser())

	def labeledruleAction(s,l,t):
		if t[0][3] == "Protocol_Rules":
			print "-----------------"
			print "- Detected rule -"
			print "-----------------"

			print t[0]
			print t[1]
			print

	labeledrule.setParseAction(labeledruleAction)

	# A complete file
	parser = OneOrMore(labeledrule)
	parser.ignore("##" + restOfLine)

	return parser
开发者ID:cascremers,项目名称:scyther,代码行数:29,代码来源:parser.py


示例9: parse_string

    def parse_string(self, string):
        '''Populate a new object from a string.
        
        Parsing is hard, so we're going to call out to the pyparsing
        library here.  I hope you installed it!
        '''
        from pyparsing import quotedString, restOfLine, Keyword, nestedExpr, OneOrMore, Word, Literal, removeQuotes
        gr_eq = Literal('=')
        gr_stripped_string = quotedString.copy().setParseAction( removeQuotes )
        gr_opt_quoted_string = gr_stripped_string | restOfLine

        def np(words, fn = gr_opt_quoted_string, action=None):
            p = Keyword(words[0], caseless=True)
            for w in words[1:]:
                p = p | Keyword(w, caseless=True)
            p = p + gr_eq + fn
            p.setParseAction(action)
            return p

        gr_line = np((NAME,), action=lambda x: self._set_name(x[2]))
        for key in self.NULL_KEYS:
            if key == id: continue
            gr_line = gr_line | np((key,), action=self._parse_setter(key))

        gr_res = OneOrMore(gr_line)
        result = gr_res.parseString(string, parseAll=True)
        return 'Console: ' + self[NAME]
开发者ID:amon-ra,项目名称:bacula_configuration,代码行数:27,代码来源:console.py


示例10: parseEqun

def parseEqun(equation):
    cForm = Word(ascii_uppercase, ascii_uppercase + ascii_lowercase + digits)
    equnExpr = Group(ZeroOrMore(cForm + Suppress('+')) + cForm)
    lhs = equnExpr.setResultsName('lhs')
    rhs = equnExpr.setResultsName('rhs')
    chemicalEqun = lhs + "->" + rhs
    parsedEqun = chemicalEqun.parseString(equation)

    LHS = parsedEqun['lhs'].asList()
    RHS = parsedEqun['rhs'].asList()

    lhsDict = {}
    rhsDict = {}

    element = Word(ascii_uppercase, ascii_lowercase)
    integer = Word(digits).setParseAction(lambda x: int(x[0]))
    elementRef = Group(element + Optional(integer, default=1))
    chemicalFormula = OneOrMore(elementRef)

    for chemical in LHS:
        lhsDict[chemical] = Counter()
        for element, count in chemicalFormula.parseString(chemical):
            lhsDict[chemical][element] += count

    for chemical in RHS:
        rhsDict[chemical] = Counter()
        for element, count in chemicalFormula.parseString(chemical):
            rhsDict[chemical][element] += count

    return lhsDict, rhsDict
开发者ID:alanhdu,项目名称:python-equation-balancing,代码行数:30,代码来源:improvedParseEqun.py


示例11: _is_running

    def _is_running(self, host):
        """Checks if a virtual machine is running.
        @param host: name of the virtual machine.
        @return: running status.
        """
        #FIXME use domstate instead
        try:
            proc = subprocess.Popen([self.options.xen.path, 'list', '-l',
                host],
                stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            output, err = proc.communicate()

            if proc.returncode != 0:
                log.debug("Xen returns error checking status for machine %s: %s"
                        % (host, err))
                return False
            data = OneOrMore(nestedExpr()).parseString(output)
            for row in data.asList()[0]:
                if row[0] == 'status' and row[1] == '2':
                    return True
            return False
        except OSError as e:
            log.warning("Xen failed to check status for machine %s: %s"
                    % (label, e))
            return False
开发者ID:khorben,项目名称:cuckoo,代码行数:25,代码来源:xen.py


示例12: parse_string

    def parse_string(self, string):
        '''Populate a new object from a string.
        
        Parsing is hard, so we're going to call out to the pyparsing
        library here.  I hope you installed it!
        '''
        from pyparsing import Suppress, Regex, quotedString, restOfLine, Keyword, nestedExpr, Group, OneOrMore, Word, Literal, alphanums, removeQuotes, replaceWith, nums
        gr_eq = Literal('=')
        gr_stripped_string = quotedString.copy().setParseAction( removeQuotes )
        gr_opt_quoted_string = gr_stripped_string | restOfLine
        gr_number = Word(nums)
        gr_yn = Keyword('yes', caseless=True).setParseAction(replaceWith('1')) | Keyword('no', caseless=True).setParseAction(replaceWith('0'))

        def np(words, fn = gr_opt_quoted_string, action=None):
            p = Keyword(words[0], caseless=True)
            for w in words[1:]:
                p = p | Keyword(w, caseless=True)
            p = p + gr_eq + fn
            p.setParseAction(action)
            return p

        gr_line = np((NAME,), action=lambda x: self._set_name(x[2]))
        gr_line = gr_line | np(PList('sd port'), gr_number, action=self._parse_setter(SDPORT))
        gr_line = gr_line | np((ADDRESS,), action=self._parse_setter(ADDRESS))
        gr_line = gr_line | np((PASSWORD,), action=self._parse_setter(PASSWORD))
        gr_line = gr_line | np((DEVICE,), action=self._parse_setter(DEVICE))
        gr_line = gr_line | np(PList('media type'), action=self._parse_setter(MEDIATYPE))
        gr_line = gr_line | np(PList('auto changer'), gr_yn, action=self._parse_setter(AUTOCHANGER))
        gr_line = gr_line | np(PList('maximum concurrent jobs'), gr_number, action=self._parse_setter(MAXIMUMCONCURRENTJOBS))
        gr_line = gr_line | np(PList('allow compression'), gr_yn, action=self._parse_setter(ALLOWCOMPRESSION))
        gr_line = gr_line | np(PList('heartbeat interval'), action=self._parse_setter(HEARTBEATINTERVAL))

        gr_res = OneOrMore(gr_line)
        result = gr_res.parseString(string, parseAll=True)
        return 'Storage: ' + self[NAME]
开发者ID:amon-ra,项目名称:bacula_configuration,代码行数:35,代码来源:storage.py


示例13: INTERFACECL_BNF

def INTERFACECL_BNF():
    """\
    pyparser grammar for the yapocis interface specification. Inspired by an IDL parser by Paul McGuire, shipped as a demo with pyparser.
    """
    global bnf
    
    if not bnf:

        # punctuation
        lbrace = Literal("{")
        rbrace = Literal("}")
        lparen = Literal("(")
        rparen = Literal(")")
        dot    = Literal(".")
        star   = Literal("*")
        semi   = Literal(";")
        
        # keywords
        boolean_   = Keyword("boolean")
        char_      = Keyword("char")
        complex64_ = Keyword("complex64")
        float_   = Keyword("float")
        float32_   = Keyword("float32")
        inout_     = Keyword("inout")
        interface_ = Keyword("interface")
        in_        = Keyword("in")
        int_     = Keyword("int")
        int16_     = Keyword("int16")
        int32_     = Keyword("int32")
        kernel_    = Keyword("kernel")
        out_       = Keyword("out")
        short_     = Keyword("short")
        uint16_     = Keyword("uint16")
        uint32_     = Keyword("uint32")
        void_      = Keyword("void")
        # Special keywords 
        alias_     = Keyword("alias")
        as_        = Keyword("as")
        outlike_   = Keyword("outlike")
        resident_  = Keyword("resident")
        widthof_   = Keyword("widthof")
        heightof_  = Keyword("heightof")
        sizeof_    = Keyword("sizeof") 
        
        identifier = Word( alphas, alphanums + "_" )
        typeName = (boolean_ ^ char_  ^ int16_ ^ int32_ ^ float32_ ^ complex64_ ^ uint16_ ^ uint32_ ^ int_ ^ float_ ^ short_)
        bufferHints = (inout_ | in_ | out_ | outlike_ | resident_ | widthof_ | heightof_ | sizeof_)
        paramlist = delimitedList( Group(bufferHints + Optional(typeName) + Optional(star) + identifier))
        interfaceItem = ((kernel_^void_^alias_^typeName) + identifier + Optional(Group(as_+identifier)) + lparen + Optional(paramlist) + rparen + semi)
        interfaceDef = Group(interface_ + identifier  + lbrace + ZeroOrMore(interfaceItem) + rbrace + semi)
        moduleItem = interfaceDef

        bnf = OneOrMore( moduleItem )
        
        singleLineComment = "//" + restOfLine
        bnf.ignore( singleLineComment )
        bnf.ignore( cStyleComment )
        
    return bnf
开发者ID:seantrue,项目名称:Yapocis,代码行数:59,代码来源:interfacecl_parser.py


示例14: read_apx

def read_apx(path):
    """Generates an alias.ArgumentationFramework from an Aspartix (.apx) file.

    Parameters
    ----------
    path : file or string
        File, directory or filename to be read.

    Returns
    -------
    framework : alias ArgumentationFramework

    Examples
    --------

    References
    ---------- 
    http://www.dbai.tuwien.ac.at/research/project/argumentation/systempage/docu.htm
    """


    try:
        from pyparsing import Word, Literal, nums, alphas, alphanums, Keyword, Group, OneOrMore, Suppress
    except ImportError:
        raise ImportError("read_apx requires pyparsing")

    if not isinstance(path, str):
        return

    # Define apx grammar
    LPAR,RPAR,DOT,COMMA = map(Suppress,"().,")
    arg,attack,pref,val,valpref,support = map(Keyword, 
        "arg att pref val valpref support".split())

    ID = Word(alphas, alphanums)
    id_pair = Group(ID + COMMA + ID)
    integer = Word(nums)
    int_pair = Group(integer + COMMA + integer)

    arg_cmd = (arg + LPAR + ID("arg*") + RPAR)
    attack_cmd = (attack + LPAR + id_pair("att*") + RPAR)
    pref_cmd = (pref + LPAR + id_pair("pref*") + RPAR)
    val_cmd = (val + LPAR + Group(ID + COMMA + integer)("val*") + RPAR)
    valpref_cmd = (valpref + LPAR + int_pair("valpref*") + RPAR)
    support_cmd = (support + LPAR + id_pair("support*") + RPAR)

    apx = OneOrMore((arg_cmd | attack_cmd | pref_cmd | val_cmd | valpref_cmd | support_cmd) + DOT)
    
    
    f = open(path, 'r')
    f = f.read()

    head, tail = ntpath.split(path)
    framework = al.ArgumentationFramework(tail)
    
    try:
        parsed = apx.parseString(f)
    except ParseException, e:
        raise al.ParsingException(e)
开发者ID:alias-org,项目名称:alias,代码行数:59,代码来源:apx.py


示例15: __init__

    def __init__(self):
        self.ALPHA_LABEL = Regex(r"alpha\[\d+\]:")
        self.LNL_LABEL = Literal("Final GAMMA-based Score of best tree")
        self.FRQ_LABEL = Regex(r"Base frequencies: (?=\d+)") ^ Regex(r"ML estimate base freqs\[\d+\]:")
        self.NAMES_LABEL = Regex(r"Partition: \d+ with name:\s+")
        self.RATES_LABEL = Regex(r"rates\[\d+\].+?:")
        self.MODEL_LABEL = Literal("Substitution Matrix:")
        self.alpha = OneOrMore(Suppress(SkipTo(self.ALPHA_LABEL)) + Suppress(self.ALPHA_LABEL) + FLOAT)
        self.lnl = Suppress(SkipTo(self.LNL_LABEL)) + Suppress(self.LNL_LABEL) + FLOAT
        self.frq = OneOrMore(Group(Suppress(SkipTo(self.FRQ_LABEL)) + Suppress(self.FRQ_LABEL) + OneOrMore(FLOAT)))
        self.names = OneOrMore(
            Suppress(SkipTo(self.NAMES_LABEL)) + Suppress(self.NAMES_LABEL) + CharsNotIn("\n") + Suppress(LineEnd())
        )
        self.rates = OneOrMore(
            Group(Suppress(SkipTo(self.RATES_LABEL)) + Suppress(self.RATES_LABEL) + OneOrMore(FLOAT))
        )
        self.model = Suppress(SkipTo(self.MODEL_LABEL)) + Suppress(self.MODEL_LABEL) + WORD

        MODEL_LABEL = Literal("Substitution Matrix:")
        SCORE_LABEL = Literal("Final GAMMA  likelihood:")
        DESC_LABEL = Literal("Model Parameters of Partition")
        NAME_LEADIN = Literal(", Name:")
        DATATYPE_LEADIN = Literal(", Type of Data:")
        ALPHA_LEADIN = Literal("alpha:")
        TREELENGTH_LEADIN = Literal("Tree-Length:")
        RATES_LABEL = Regex(r"rate \w <-> \w:")
        FREQS_LABEL = Regex(r"freq pi\(\w\):")

        model = Suppress(SkipTo(MODEL_LABEL)) + Suppress(MODEL_LABEL) + WORD
        likelihood = Suppress(SkipTo(SCORE_LABEL)) + Suppress(SCORE_LABEL) + FLOAT
        description = (
            Suppress(SkipTo(DESC_LABEL))
            + Suppress(DESC_LABEL)
            + INT
            + Suppress(NAME_LEADIN)
            + SPACEDWORD
            + Suppress(DATATYPE_LEADIN)
            + WORD
        )
        alpha = Suppress(ALPHA_LEADIN) + FLOAT
        rates = Suppress(RATES_LABEL) + FLOAT
        freqs = Suppress(FREQS_LABEL) + FLOAT

        self._dash_f_e_parser = (
            Group(OneOrMore(model))
            + likelihood
            + Group(
                OneOrMore(
                    Group(
                        description
                        + alpha
                        + Suppress(TREELENGTH_LEADIN)
                        + Suppress(FLOAT)
                        + Group(OneOrMore(rates))
                        + Group(OneOrMore(freqs))
                    )
                )
            )
        )
开发者ID:DessimozLab,项目名称:treeCl,代码行数:59,代码来源:parsers.py


示例16: analyzeVerse

def analyzeVerse(instr):
   swp = swap_agaram(unicode(instr))
   parse_syntax = OneOrMore(adi).leaveWhitespace()
   try:
      result = parse_syntax.parseString(swp, parseAll=True)
      return generateXML(result)
   except Exception,e:
      return None
开发者ID:justjkk,项目名称:visaineri-parsers,代码行数:8,代码来源:tamil_parser.py


示例17: parse_string

    def parse_string(self, string):
        '''Populate a new object from a string.
        
        Parsing is hard, so we're going to call out to the pyparsing
        library here.  I hope you installed it!
        '''
        from pyparsing import quotedString, restOfLine, Keyword, nestedExpr, OneOrMore, Word, Literal, removeQuotes, nums, replaceWith, printables
        gr_eq = Literal('=')
        gr_stripped_string = quotedString.copy().setParseAction( removeQuotes )
        gr_opt_quoted_string = gr_stripped_string | restOfLine
        gr_number = Word(nums)
        gr_yn = Keyword('yes', caseless=True).setParseAction(replaceWith('1')) | Keyword('no', caseless=True).setParseAction(replaceWith('0'))

        def _handle_ip(*x):
            a,b,c =  x[2]
            return '  %s = { %s }' % (a,c[0])

        def _handle_fdaddr(*x):
            a,b,c =  x[2]
            self._set(FDADDRESSES, '  %s' % '\n  '.join(c))
            return

        def np(words, fn = gr_opt_quoted_string, action=None):
            p = Keyword(words[0], caseless=True)
            for w in words[1:]:
                p = p | Keyword(w, caseless=True)
            p = p + gr_eq + fn
            p.setParseAction(action)
            return p

        gr_line = np((NAME,), action=lambda x: self._set_name(x[2]))
        gr_line = gr_line | np((ADDRESS,), action=self._parse_setter(ADDRESS))
        gr_line = gr_line | np((CATALOG,), action=self._parse_setter(CATALOG_ID, dereference=True))
        gr_line = gr_line | np((PASSWORD,), action=self._parse_setter(PASSWORD))
        gr_line = gr_line | np(PList('file retention'), action=self._parse_setter(FILERETENTION))
        gr_line = gr_line | np(PList('job retention'), action=self._parse_setter(JOBRETENTION))
        gr_line = gr_line | np((PRIORITY,), gr_number, action=self._parse_setter(PRIORITY))
        gr_line = gr_line | np(PList('working directory'), action=self._parse_setter(WORKINGDIRECTORY))
        gr_line = gr_line | np(PList('pid directory'), action=self._parse_setter(PIDDIRECTORY))
        gr_line = gr_line | np(PList('heart beat interval'), action=self._parse_setter(HEARTBEATINTERVAL))
        gr_line = gr_line | np(PList('fd address'), action=self._parse_setter(FDADDRESS))
        gr_line = gr_line | np(PList('fd source address'), action=self._parse_setter(FDSOURCEADDRESS))
        gr_line = gr_line | np(PList('pki key pair'), action=self._parse_setter(PKIKEYPAIR))
        gr_line = gr_line | np(PList('pki master key'), action=self._parse_setter(PKIMASTERKEY))
        gr_line = gr_line | np(PList('fd port'), gr_number, action=self._parse_setter(FDPORT))
        gr_line = gr_line | np(PList('auto prune'), gr_yn, action=self._parse_setter(AUTOPRUNE))
        gr_line = gr_line | np(PList('maximum concurrent jobs'), gr_number, action=self._parse_setter(FDPORT))
        gr_line = gr_line | np(PList('pki encryption'), gr_yn, action=self._parse_setter(PKIENCRYPTION))
        gr_line = gr_line | np(PList('pki signatures'), gr_yn, action=self._parse_setter(PKISIGNATURES))

        # This is a complicated one
        da_addr = np(('Addr','Port'), Word(printables), lambda x,y,z: ' '.join(z))
        da_ip = np(('IPv4','IPv6','IP'), nestedExpr('{','}', OneOrMore(da_addr).setParseAction(lambda x,y,z: ' ; '.join(z)))).setParseAction(_handle_ip)
        da_addresses = np(('fd addresses', FDADDRESSES), nestedExpr('{','}', OneOrMore(da_ip)), _handle_fdaddr)

        gr_res = OneOrMore(gr_line|da_addresses)
        result = gr_res.parseString(string, parseAll=True)
        return 'Client: ' + self[NAME]
开发者ID:amon-ra,项目名称:bacula_configuration,代码行数:58,代码来源:client.py


示例18: expression

def expression():
    """
    """
    def transformer(string, location, tokens):
        return tokens.asList()
    token = OneOrMore(term())
    token.setName("expression")
    token.setParseAction(transformer)
    return token
开发者ID:extesla,项目名称:dice-python,代码行数:9,代码来源:grammar.py


示例19: get_highlight_expression

def get_highlight_expression():
    field_expression = Word(srange("[a-zA-Z0-9_.*]"))
    field_expression.setParseAction(parse_highlight_field_expression)
    fields_expression = OneOrMore(
        field_expression + Optional(',').suppress())
    fields_expression.setParseAction(parse_highlight_expression)
    highlight_expression = Word('highlight:').suppress() \
        + Word('[').suppress() \
        + fields_expression + Word(']').suppress()
    return highlight_expression
开发者ID:Aplopio,项目名称:plasticparser,代码行数:10,代码来源:tokenizer.py


示例20: manyXYZ

def manyXYZ(pathXYZ):
    """
    Read one or more molecular geometries in XYZ format from a file.

    :param: pathXYZ
    :type:  string
    :return: [[AtomXYZ]]
    """
    manyMol = OneOrMore(Group(parser_xyz))
    xss = manyMol.parseFile(pathXYZ)
    return list(map(createAtoms, xss))
开发者ID:SCM-NV,项目名称:qmworks,代码行数:11,代码来源:xyzParser.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python pyparsing.ParserElement类代码示例发布时间:2022-05-27
下一篇:
Python pyparsing.Literal类代码示例发布时间: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