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


Python Word.setResultsName方法代码示例

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


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

示例1: getLogLineBNF_DBpedia36

# 需要导入模块: from pyparsing import Word [as 别名]
# 或者: from pyparsing.Word import setResultsName [as 别名]
def getLogLineBNF_DBpedia36():
    global logLineBNF
    
    if logLineBNF is None:
        integer = Word( nums )
        ipAddress = delimitedList( integer, ".", combine=True )
        hashipAddress = Word(nums+alphas)
        timeZoneOffset = Word("+-",nums)
        month = Word(string.uppercase, string.lowercase, exact=3)
        serverDateTime = Group( Suppress("[") + 
                                Combine( integer + "/" + month + "/" + integer +
                                        " " + integer + ":" + integer + ":" + integer ) +
                                timeZoneOffset + 
                                Suppress("]") )
                         
        logLineBNF = ( hashipAddress.setResultsName("ipAddr") + 
                       Suppress("-") +
                       ("-" | Word( alphas+nums+"@._" )).setResultsName("auth") +
                       serverDateTime.setResultsName("timestamp") + 
                       dblQuotedString.setResultsName("cmd").setParseAction(getCmdFields2) +
                       (integer | "-").setResultsName("statusCode") + 
                       (integer | "-").setResultsName("numBytesSent")  + 
                       dblQuotedString.setResultsName("referrer").setParseAction(removeQuotes) +
                       dblQuotedString.setResultsName("clientSfw").setParseAction(removeQuotes) )
    return logLineBNF
开发者ID:imclab,项目名称:lod_analysis,代码行数:27,代码来源:parse_tools.py

示例2: parse_morse_letter

# 需要导入模块: from pyparsing import Word [as 别名]
# 或者: from pyparsing.Word import setResultsName [as 别名]
def parse_morse_letter(line):
    """Parse a line of input from the morse code table file and convert it into a parsetree."""
    letter = Word(alphas)
    token = Word(alphas)
    morse_letter_expression = letter.setResultsName('letter')\
                            + OneOrMore(token).setResultsName('tokens')
    return morse_letter_expression.parseString(line)
开发者ID:asgeirbjarnason,项目名称:arduino_morse_code,代码行数:9,代码来源:translation.py

示例3: parse_sexp

# 需要导入模块: from pyparsing import Word [as 别名]
# 或者: from pyparsing.Word import setResultsName [as 别名]
    def parse_sexp(data):
        '''parse sexp/S-expression format and return a python list'''
        # define punctuation literals
        LPAR, RPAR, LBRK, RBRK, LBRC, RBRC, VBAR = map(Suppress, "()[]{}|")

        decimal = Word("123456789", nums).setParseAction(lambda t: int(t[0]))
        bytes = Word(printables)
        raw = Group(decimal.setResultsName("len") + Suppress(":") + bytes).setParseAction(OtrPrivateKeys.verifyLen)
        token = Word(alphanums + "-./_:*+=")
        base64_ = Group(Optional(decimal, default=None).setResultsName("len") + VBAR
            + OneOrMore(Word( alphanums +"+/=" )).setParseAction(lambda t: b64decode("".join(t)))
            + VBAR).setParseAction(OtrPrivateKeys.verifyLen)

        hexadecimal = ("#" + OneOrMore(Word(hexnums)) + "#")\
                        .setParseAction(lambda t: int("".join(t[1:-1]),16))
        qString = Group(Optional(decimal, default=None).setResultsName("len") +
                                dblQuotedString.setParseAction(removeQuotes)).setParseAction(OtrPrivateKeys.verifyLen)
        simpleString = raw | token | base64_ | hexadecimal | qString

        display = LBRK + simpleString + RBRK
        string_ = Optional(display) + simpleString

        sexp = Forward()
        sexpList = Group(LPAR + ZeroOrMore(sexp) + RPAR)
        sexp << ( string_ | sexpList )

        try:
            sexpr = sexp.parseString(data)
            return sexpr.asList()[0][1:]
        except ParseFatalException, pfe:
            print("Error:", pfe.msg)
            print(pfe.loc)
            print(pfe.markInputline())
开发者ID:a-u-me,项目名称:keysync,代码行数:35,代码来源:otr_private_key.py

示例4: parse_connection_str

# 需要导入模块: from pyparsing import Word [as 别名]
# 或者: from pyparsing.Word import setResultsName [as 别名]
def parse_connection_str(connstr):
    ## Grammar for connection syntax
    digits="0123456789"
    othervalid="[email protected]"
    identifier= Word(alphas+digits+othervalid)
    nodename=identifier.setResultsName('nodename')

    outputnames = delimitedList( identifier ).setResultsName('outputnames')
    inputnames  = delimitedList( identifier ).setResultsName('inputnames')

    # middle nodes have both inputs and outputs
    middlenode= Group( nodename + Suppress('(') + inputnames
                       + Optional( "|" + outputnames)
                       + Suppress(")") ).setResultsName('middlenode')
    # first node has only outputs
    headnode = (nodename + Suppress("(") + outputnames
                + Suppress(")")).setResultsName('headnode')
    # last node has only inputs
    tailnode = (nodename + Suppress("(") + inputnames
                + Suppress(")")).setResultsName('tailnode')

    # connect head -> [middle ->] tail
    connect= Group( headnode
                    + Group(ZeroOrMore(Suppress("->") \
                        + middlenode + FollowedBy("->") )).setResultsName('middlenodes')
                    + Suppress("->")+tailnode).setResultsName('nodes')

    connectlist = Group( connect + ZeroOrMore( Suppress(";")\
                        + connect )).setResultsName('connects')

    parsed=connectlist.parseString(connstr)
    check_numconnections(parsed)
    return parsed
开发者ID:ihrke,项目名称:nipype_connect_str,代码行数:35,代码来源:nipype_connect_str.py

示例5: parse_ampersand_comment

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

示例6: nexus_iter

# 需要导入模块: from pyparsing import Word [as 别名]
# 或者: from pyparsing.Word import setResultsName [as 别名]
def nexus_iter(infile):
    import pyparsing
    pyparsing.ParserElement.enablePackrat()
    from pyparsing import Word, Literal, QuotedString, CaselessKeyword, \
         OneOrMore, Group, Optional, Suppress, Regex, Dict
    ## beginblock = Suppress(CaselessKeyword("begin") +
    ##                       CaselessKeyword("trees") + ";")
    ## endblock = Suppress((CaselessKeyword("end") |
    ##                      CaselessKeyword("endblock")) + ";")
    comment = Optional(Suppress("[&") + Regex(r'[^]]+') + Suppress("]"))
    ## translate = CaselessKeyword("translate").suppress()
    name = Word(string.letters+string.digits+"_.") | QuotedString("'")
    ## ttrec = Group(Word(string.digits).setResultsName("number") +
    ##               name.setResultsName("name") +
    ##               Optional(",").suppress())
    ## ttable = Group(translate + OneOrMore(ttrec) + Suppress(";"))
    newick = Regex(r'[^;]+;')
    tree = (CaselessKeyword("tree").suppress() +
            Optional("*").suppress() +
            name.setResultsName("tree_name") +
            comment.setResultsName("tree_comment") +
            Suppress("=") +
            comment.setResultsName("root_comment") +
            newick.setResultsName("newick"))
    ## treesblock = Group(beginblock +
    ##                    Optional(ttable.setResultsName("ttable")) +
    ##                    Group(OneOrMore(tree)) +
    ##                    endblock)

    def not_begin(s): return s.strip().lower() != "begin trees;"
    def not_end(s): return s.strip().lower() not in ("end;", "endblock;")
    def parse_ttable(f):
        ttable = {}
        while True:
            s = f.next().strip()
            if not s: continue
            if s.lower() == ";": break
            if s[-1] == ",": s = s[:-1]
            k, v = s.split()
            ttable[k] = v
            if s[-1] == ";": break
        return ttable
            
    # read lines between "begin trees;" and "end;"
    f = itertools.takewhile(not_end, itertools.dropwhile(not_begin, infile))
    s = f.next().strip().lower()
    if s != "begin trees;":
        print sys.stderr, "Expecting 'begin trees;', got %s" % s
        raise StopIteration
    ttable = {}
    while True:
        try: s = f.next().strip()
        except StopIteration: break
        if not s: continue
        if s.lower() == "translate":
            ttable = parse_ttable(f)
            print "ttable: %s" % len(ttable)
        elif s.split()[0].lower()=='tree':
            match = tree.parseString(s)
            yield nexus.Newick(match, ttable)
开发者ID:ChriZiegler,项目名称:cython-experiments-1,代码行数:62,代码来源:newick.py

示例7: setup

# 需要导入模块: from pyparsing import Word [as 别名]
# 或者: from pyparsing.Word import setResultsName [as 别名]
    def setup(self):
        # some expressions that will be reused
        units = []
        for unit in time_units:
            units.append(Keyword(unit))
        units = get_match_first(units)
        units = units.setResultsName("unit")
        units.setParseAction(lambda s, l, tok: time_units[tok[0]])

        multiplier = Word(nums)
        multiplier = multiplier.setResultsName("multiply")
        multiplier.setParseAction(self.parseMulti)

        adder = []
        for add in add_modifiers:
            adder.append(CL(add))
        adder = get_match_first(adder)
        adder = adder.setResultsName("add")
        adder.setParseAction(self.parseAdd)
        modifier = (multiplier | adder)  # + FollowedBy(units)

        # ago
        #
        # e.g 5 days ago
        ago = Optional(modifier) + units + Suppress(Word("ago"))
        ago.setParseAction(self.parseAgo)

        # time range
        #
        # e.g in the lat 10 days
        time_range = Suppress(Optional(
            CL("in the"))) + \
            Suppress(Word("last") |
                     Word("past")) + \
            Optional(modifier) + \
            units
        time_range.setParseAction(self.parseRange)

        # special keyword handling
        #
        # e.g yesterday
        # only handles yesterday right now, maybe need to be modified to do
        # more
        special_expr = []
        for expr in special:
            special_expr.append(
                Keyword(expr).setParseAction(
                    lambda s, l, tok: special[tok[0]]))
        special_expr = get_match_first(special_expr)
        special_expr = special_expr.setResultsName("unit")
        special_expr.setParseAction(self.parseAgo)

        parser = (special_expr | ago | time_range)

        return parser
开发者ID:haystack,项目名称:eyebrowse-server,代码行数:57,代码来源:date_parser.py

示例8: parseTypes

# 需要导入模块: from pyparsing import Word [as 别名]
# 或者: from pyparsing.Word import setResultsName [as 别名]
def parseTypes(path):
  msgs = set()
  types = {}

  for line in lineGen(path):
    number = Word(nums)
    word = Word(alphanums + "-_")

    wordList = Forward()
    wordList = word + ZeroOrMore(',' + word)

    par = (Literal('NetworkPartition').setResultsName('type') +\
      '(' + Literal('Set') + '(' +\
      wordList.setResultsName('p1') + ')' + ',' +\
      Literal('Set') + '(' +\
      wordList.setResultsName('p2') + ')' + \
      ')')

    subType = (word + Optional(nestedExpr('(', ')'))).setResultsName('msg')
    msg = (Literal('MsgEvent').setResultsName('type') +\
       '(' + word.setResultsName('src') + ',' +\
       word.setResultsName('dst') + ',' +\
       subType  + ')')

    event = Word( nums ) +\
      Literal('Unique') + "(" + (msg | par) + ',' +\
      number.setResultsName('uid')  + ')'

    result = event.parseString(line)

    key = result.uid
    if result.type == 'MsgEvent':
      msg = list2tuple( result.msg.asList() )
      value = (result.type, result.src, result.dst, msg)
      msgs.add(msg)
    elif result.type == 'NetworkPartition':
      value = (result.type, result.p1, result.p2)

    types[key] = value

  return types
开发者ID:jackzhao-mj,项目名称:distributed_examples,代码行数:43,代码来源:parse.py

示例9: fromString

# 需要导入模块: from pyparsing import Word [as 别名]
# 或者: from pyparsing.Word import setResultsName [as 别名]
	def fromString(inputText, verbose=False):
		if verbose: print 'Verbose:', verbose
		text = nestedExpr("/*", "*/").suppress().transformString(inputText) 

		semicolon = Suppress(Word(";"))
		quote     = Suppress(Word("\""))
		op        = Suppress(Word("{"))
		cl        = Suppress(Word("}"))
		opp       = Suppress(Word("("))
		clp       = Suppress(Word(")"))
		
		identifier = Word( alphas+"_", alphanums+"_" )
		commIdentifier = Group(identifier.setResultsName('identifier') + Optional(opp + (CaselessLiteral("ice")|CaselessLiteral("ros")).setResultsName("type") + clp))

		# Imports
		idslImport  = Suppress(CaselessLiteral("import")) + quote +  CharsNotIn("\";").setResultsName('path') + quote + semicolon
		idslImports = ZeroOrMore(idslImport)
		# Communications
		implementsList = Group(CaselessLiteral('implements')    + identifier + ZeroOrMore(Suppress(Word(',')) + identifier) + semicolon)
		requiresList   = Group(CaselessLiteral('requires')      + identifier + ZeroOrMore(Suppress(Word(',')) + identifier) + semicolon)
		subscribesList = Group(CaselessLiteral('subscribesTo')  + commIdentifier + ZeroOrMore(Suppress(Word(',')) + commIdentifier) + semicolon)
		publishesList  = Group(CaselessLiteral('publishes')     + identifier + ZeroOrMore(Suppress(Word(',')) + identifier) + semicolon)
		communicationList = implementsList | requiresList | subscribesList | publishesList
		communications = Group( Suppress(CaselessLiteral("communications")) + op + ZeroOrMore(communicationList) + cl + semicolon)
		
		# Language
		language = Suppress(CaselessLiteral("language")) + (CaselessLiteral("cpp")|CaselessLiteral("python")) + semicolon
		# GUI
		gui = Group(Optional(Suppress(CaselessLiteral("gui")) + CaselessLiteral("Qt") + opp + identifier + clp + semicolon ))
		# additional options
		options = Group(Optional(Suppress(CaselessLiteral("options")) + identifier + ZeroOrMore(Suppress(Word(',')) + identifier) + semicolon))
		
		componentContents = communications.setResultsName('communications') & language.setResultsName('language') & gui.setResultsName('gui') & options.setResultsName('options')
		component = Suppress(CaselessLiteral("component")) + identifier.setResultsName("name") + op + componentContents.setResultsName("properties") + cl + semicolon

		CDSL = idslImports.setResultsName("imports") + component.setResultsName("component")
		CDSL.ignore( cppStyleComment )
		tree = CDSL.parseString(text)
		return CDSLParsing.component(tree)
开发者ID:soura97,项目名称:robocomp,代码行数:41,代码来源:parseCDSL.py

示例10: makeNewickParser

# 需要导入模块: from pyparsing import Word [as 别名]
# 或者: from pyparsing.Word import setResultsName [as 别名]
    def makeNewickParser():
        # pyparsing
        from pyparsing import Combine, Optional, Literal, CaselessLiteral, \
                           Word, alphanums, \
                           nums, oneOf, Group, Dict, Forward, \
                           ParseResults, CharsNotIn, ZeroOrMore


        # literals
        lparen    = Literal("(").suppress()
        rparen    = Literal(")").suppress()
        colon     = Literal(":").suppress()
        semicolon = Literal(":").suppress()
        comma     = Literal(",").suppress()
        point     = Literal(".")
        e         = CaselessLiteral("E")


        # terminal rules
        name    = Word(alphanums + "_" + "-" + "." + "+")
        fnumber = Combine(Word("+-"+nums, nums) + 
                          Optional(point + Optional(Word(nums))) +
                          Optional(e + Word("+-"+nums, nums)))
        dist      = fnumber
        bootstrap = fnumber


        # recursive rules
        subtree = Forward()
        subtreelist = Forward()

        subtree << \
            Group(
                (
                    (lparen + subtreelist + rparen).setResultsName("subtree") |
                    name.setResultsName("name")
                ) +
                Optional(
                    CharsNotIn(",);").setResultsName("data")
                )
            )
        subtreelist << subtree + Optional(comma + subtreelist)


        # top level rule
        tree = subtree + Word(";").suppress()


        return tree.parseString
开发者ID:brantp,项目名称:py_util,代码行数:51,代码来源:treelib.py

示例11: receiver_input_rule

# 需要导入模块: from pyparsing import Word [as 别名]
# 或者: from pyparsing.Word import setResultsName [as 别名]
        def receiver_input_rule():
            path = Combine(ZeroOrMore(word + ".") + word)
            input = path.setResultsName("input")

            operator = oneOf(operators.keys()).setResultsName("operator")
            value = path.setResultsName("value")
            comparison = operator + value

            is_or_was = Word("is") | Word("was")

            condition = Group(input + is_or_was.setResultsName("temporal") + comparison)
            res = ZeroOrMore(condition + _and) + condition
            conditions = Group(res).setResultsName("conditions")

            return Optional("always").setResultsName("always_fire_rule") + when + conditions + then + actions
开发者ID:abultman,项目名称:PiAutomator,代码行数:17,代码来源:RuleParser.py

示例12: fromString

# 需要导入模块: from pyparsing import Word [as 别名]
# 或者: from pyparsing.Word import setResultsName [as 别名]
	def fromString(inputText, verbose=False):
		if verbose: print 'Verbose:', verbose
		text = nestedExpr("/*", "*/").suppress().transformString(inputText)

		semicolon = Suppress(Word(";"))
		quote     = Suppress(Word("\""))
		op        = Suppress(Word("{"))
		cl        = Suppress(Word("}"))
		opp       = Suppress(Word("("))
		clp       = Suppress(Word(")"))
		lt       = Suppress(Word("<"))
		gt       = Suppress(Word(">"))
		identifier     = Word(alphas+"_",alphanums+"_")
		typeIdentifier = Word(alphas+"_",alphanums+"_:")


		## Imports
		idslImport  = Suppress(Word("import")) + quote +  CharsNotIn("\";").setResultsName('path') + quote + semicolon
		idslImports = ZeroOrMore(idslImport)


		dictionaryDef = Word("dictionary") + lt + CharsNotIn("<>;") + gt + identifier.setResultsName('name') + semicolon
		sequenceDef   = Word("sequence")   + lt + CharsNotIn("<>;") + gt + identifier.setResultsName('name') + semicolon
		enumDef       = Word("enum")       + identifier.setResultsName('name') + op + CharsNotIn("{}") + cl + semicolon
		structDef     = Word("struct")     + identifier.setResultsName('name') + op + CharsNotIn("{}") + cl + semicolon
		exceptionDef  = Word("exception")  + identifier.setResultsName('name') + op + CharsNotIn("{}") + cl + semicolon

		raiseDef       = Suppress(Word("throws")) + typeIdentifier + ZeroOrMore( Literal(',') + typeIdentifier )
		decoratorDef    = Literal('idempotent') | Literal('out')
		retValDef       = typeIdentifier.setResultsName('ret')

		firstParam    = Group( Optional(decoratorDef.setResultsName('decorator')) + typeIdentifier.setResultsName('type') + identifier.setResultsName('name'))
		nextParam     = Suppress(Word(',')) + firstParam
		params        = firstParam + ZeroOrMore(nextParam)


		remoteMethodDef  = Group(Optional(decoratorDef) + retValDef + typeIdentifier.setResultsName('name') + opp + Optional(          params).setResultsName('params') + clp + Optional(raiseDef) + semicolon )
		interfaceDef    = Word("interface")  + typeIdentifier.setResultsName('name') + op + Group(ZeroOrMore(remoteMethodDef)) + cl + semicolon

		moduleContent = Group(structDef | enumDef | exceptionDef | dictionaryDef | sequenceDef | interfaceDef)
		module = Suppress(Word("module")) + identifier.setResultsName("name") + op + ZeroOrMore(moduleContent).setResultsName("contents") + cl + semicolon

		IDSL = idslImports.setResultsName("imports") + module.setResultsName("module")
		IDSL.ignore( cppStyleComment )
		tree = IDSL.parseString(text)
		return IDSLParsing.module(tree)
开发者ID:BasilMVarghese,项目名称:robocomp,代码行数:48,代码来源:parseIDSL.py

示例13: urlsplit

# 需要导入模块: from pyparsing import Word [as 别名]
# 或者: from pyparsing.Word import setResultsName [as 别名]
def urlsplit(url, scheme='', allow_fragments=1):
    """Parse a URL into 5 components:
    <scheme>://<netloc>/<path>?<query>#<fragment>
    Return a 5-tuple: (scheme, netloc, path, query, fragment).
    Note that we don't break the components up in smaller bits
    (e.g. netloc is a single string) and we don't expand % escapes."""
    global _urlBNF
    
    key = url, scheme, allow_fragments
    cached = _parse_cache.get(key, None)
    if cached:
        return cached
    if len(_parse_cache) >= MAX_CACHE_SIZE: # avoid runaway growth
        clear_cache()
    
    if (_urlBNF is None):
        scheme_chars = alphanums + "+-."
        urlscheme = Word( scheme_chars )
        netloc_chars = "".join( [ c for c in printables if c not in "/." ] )
        netloc = Combine(delimitedList( Word( netloc_chars ), ".", combine=True ))
        path_chars = "".join( [ c for c in printables if c not in "?" ] )
        path = Word( path_chars )
        query_chars = "".join( [ c for c in printables if c not in "#" ] )
        query = Word( query_chars )
        fragment = Word( printables+" " )
        _urlBNF = Combine(Optional(urlscheme.setResultsName("scheme") + ":" ) + 
                          Optional(Literal("//").suppress() + netloc, default="").setResultsName("netloc") + 
                          Optional(path.setResultsName("path"), default="") +
                          Optional(Literal("?").suppress()  + query, default="").setResultsName("query") + 
                          Optional(Literal("#").suppress()  + fragment, default="").setResultsName("fragment") )
        
    tokens = _urlBNF.parseString( url )

    tuple = (tokens.scheme or scheme), tokens.netloc[0], tokens.path, tokens.query[0], tokens.fragment[0]
    _parse_cache[key] = tuple
    return tuple
开发者ID:La-Lojban,项目名称:Lojban-Translator,代码行数:38,代码来源:pyparsing_test.py

示例14: parse_treesblock

# 需要导入模块: from pyparsing import Word [as 别名]
# 或者: from pyparsing.Word import setResultsName [as 别名]
def parse_treesblock(infile):
    import string
    from pyparsing import Optional, Word, Regex, CaselessKeyword, Suppress
    from pyparsing import QuotedString
    comment = Optional(Suppress("[&") + Regex(r'[^]]+') + Suppress("]"))
    name = Word(alphanums+"_") | QuotedString("'")
    newick = Regex(r'[^;]+;')
    tree = (CaselessKeyword("tree").suppress() +
            Optional("*").suppress() +
            name.setResultsName("tree_name") +
            comment.setResultsName("tree_comment") +
            Suppress("=") +
            comment.setResultsName("root_comment") +
            newick.setResultsName("newick"))
    ## treesblock = Group(beginblock +
    ##                    Optional(ttable.setResultsName("ttable")) +
    ##                    Group(OneOrMore(tree)) +
    ##                    endblock)

    def parse_ttable(f):
        ttable = {}
        while True:
            s = f.next().strip()
            if s.lower() == ";":
                break
            if s[-1] in ",;":
                s = s[:-1]
            k, v = s.split()
            ttable[k] = v
            if s[-1] == ";":
                break
        return ttable

    ttable = {}
    while True:
        try:
            s = infile.next().strip()
        except StopIteration:
            break
        if s.lower() == "translate":
            ttable = parse_ttable(infile)
            # print("ttable: %s" % len(ttable))
        else:
            match = tree.parseString(s)
            yield Newick(match, ttable)
开发者ID:rhr,项目名称:ivy,代码行数:47,代码来源:nexus.py

示例15: _get_handbrake_title_pattern

# 需要导入模块: from pyparsing import Word [as 别名]
# 或者: from pyparsing.Word import setResultsName [as 别名]
    def _get_handbrake_title_pattern(self):
        title = Literal("+ title").suppress()
        integer = Word("0123456789")
        time = Combine(integer + ":" + integer + ":" + integer)
        duration = Literal("+ duration:").suppress()
        subtitle = Literal("+ subtitle tracks:")
        iso = Literal('(iso639-2:').suppress() + Word(alphas)
        subtitle_track = Literal("+").suppress() + Group(integer + SkipTo(iso).suppress() + iso) + restOfLine.suppress()

        title_num = integer.setResultsName("title")
        duration_num = time.setResultsName("duration")
        subtitles = Group(ZeroOrMore(subtitle_track)).setResultsName("subtitles")

        pattern = title + title_num + \
            SkipTo(duration).suppress() + \
            duration + duration_num + \
            SkipTo(subtitle).suppress() + subtitle.suppress() + subtitles
            
        return pattern
开发者ID:jeffreyparker,项目名称:brakejob,代码行数:21,代码来源:brakejob.py


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