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

Python pyparsing.replaceWith函数代码示例

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

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



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

示例1: get_parser_atoms

 def get_parser_atoms(self):
     """ Function defining the atoms of the grammar """
     atoms = super(LanguageMathematica, self).get_parser_atoms()
     atoms['assign'] = (Literal("=") | Literal(":=") | Literal("=="))
     atoms['consts'] = Keyword("Pi").setParseAction(replaceWith('PI')) |\
                       Keyword("E").setParseAction(replaceWith('E'))
     return atoms
开发者ID:david-zwicker,项目名称:convert-formula,代码行数:7,代码来源:language.py


示例2: jsParse

def jsParse(inStr):
	# This disaster is a context-free grammar parser for parsing javascript object literals.
	# It needs to be able to handle a lot of the definitional messes you find in in-the-wild
	# javascript object literals.
	# Unfortunately, Javascript is /way/ more tolerant then JSON when it comes to object literals
	# so we can't just parse objects using python's `json` library.

	TRUE = pp.Keyword("true").setParseAction( pp.replaceWith(True) )
	FALSE = pp.Keyword("false").setParseAction( pp.replaceWith(False) )
	NULL = pp.Keyword("null").setParseAction( pp.replaceWith(None) )

	jsonString = pp.quotedString.setParseAction( pp.removeQuotes )
	jsonNumber = pp.Combine( pp.Optional('-') + ( '0' | pp.Word('123456789',pp.nums) ) +
											pp.Optional( '.' + pp.Word(pp.nums) ) +
											pp.Optional( pp.Word('eE',exact=1) + pp.Word(pp.nums+'+-',pp.nums) ) )

	jsonObject   = pp.Forward()
	jsonValue    = pp.Forward()
	jsonDict     = pp.Forward()
	jsonArray    = pp.Forward()
	jsonElements = pp.Forward()

	rawText      = pp.Regex('[a-zA-Z_$][0-9a-zA-Z_$]*')

	commaToNull = pp.Word(',,', exact=1).setParseAction(pp.replaceWith(None))
	jsonElements << pp.ZeroOrMore(commaToNull) + pp.Optional(jsonObject) + pp.ZeroOrMore((pp.Suppress(',') + jsonObject) | commaToNull)

	jsonValue << ( jsonString | jsonNumber | TRUE | FALSE | NULL )


	dictMembers = pp.delimitedList( pp.Group( (rawText | jsonString) + pp.Suppress(':') + (jsonValue | jsonDict | jsonArray)))
	jsonDict << ( pp.Dict( pp.Suppress('{') + pp.Optional(dictMembers) + pp.ZeroOrMore(pp.Suppress(',')) + pp.Suppress('}') ) )
	jsonArray << ( pp.Group(pp.Suppress('[') + pp.Optional(jsonElements) + pp.Suppress(']') ) )
	jsonObject << (jsonValue | jsonDict | jsonArray)

	jsonComment = pp.cppStyleComment
	jsonObject.ignore( jsonComment )

	def convertDict(s, l, toks):

		return dict(toks.asList())

	def convertNumbers(s,l,toks):
		n = toks[0]
		try:
			return int(n)
		except ValueError:
			return float(n)

	jsonNumber.setParseAction(convertNumbers)
	jsonDict.setParseAction(convertDict)

	# jsonObject.setDebug()
	jsonObject.parseString('"inStr"').pop()
	return jsonObject.parseString(inStr).pop()
开发者ID:GJdan,项目名称:MangaCMS,代码行数:55,代码来源:jsLiteralParse.py


示例3: date

def date(name=None, compulsory=False):
    """
    Creates the grammar for a Date (D) field, accepting only numbers in a certain pattern.

    The field can be compulsory, in which case the empty date, composed only of zeros, is disallowed.

    :param name: name for the field
    :param compulsory: indicates if the empty date is disallowed
    :return: grammar for the date field
    """

    if name is None:
        name = 'Date Field'

    # Basic field
    # This regex allows values from 00000101 to 99991231
    field = pp.Regex('[0-9][0-9][0-9][0-9](0[1-9]|1[0-2])(0[1-9]|[1-2][0-9]|3[0-1])')

    # Parse action
    field.setParseAction(lambda d: datetime.datetime.strptime(d[0], '%Y%m%d').date())

    # Name
    field.setName(name)

    if not compulsory:
        # If it is not compulsory the empty date is accepted
        optional = pp.Regex('[0]{8}')
        optional.setParseAction(pp.replaceWith(None))

        # Name
        optional.setName(name)

        # If it is not compulsory the empty date is accepted
        empty = pp.Regex('[ ]{8}')
        empty.setParseAction(pp.replaceWith(None))

        # Name
        empty.setName(name)

        field = field | optional | empty

        # Name
        field.setName(name)

    # White spaces are not removed
    field.leaveWhitespace()

    return field
开发者ID:toddrimes,项目名称:CWR-DataApi,代码行数:48,代码来源:basic.py


示例4: 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


示例5: 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


示例6: ipi_name_number

def ipi_name_number(name=None, compulsory=False):
    """
    IPI Name Number field.

    An IPI Name Number is composed of eleven digits.

    So, for example, an IPI Name Number code field can contain 00014107338.

    :param name: name for the field
    :param compulsory: indicates if the empty string is disallowed
    :return: a parser for the IPI Name Number field
    """

    if name is None:
        name = 'IPI Name Number Field'

    field = basic.numeric(11, compulsory=compulsory)

    if not compulsory:
        # If it is not compulsory then it can be set as empty
        empty = pp.Regex('[ ]{11}')
        empty.setParseAction(pp.replaceWith(None))
        empty.setName(name)

        field = empty | field
        # Name
        field.setName(name)

    field.setName(name)

    return field.setResultsName('ipi_name_n')
开发者ID:toddrimes,项目名称:CWR-DataApi,代码行数:31,代码来源:special.py


示例7: audio_visual_key

def audio_visual_key(name=None):
    """
    Creates the grammar for an Audio Visual Key code.

    This is a variation on the ISAN (International Standard Audiovisual Number)

    :param name: name for the field
    :return: grammar for an ISRC field
    """

    if name is None:
        name = 'AVI Field'

    society_code = basic.numeric(3)
    society_code = society_code.setName('Society Code') \
        .setResultsName('society_code')

    av_number = basic.alphanum(15)
    field_empty = pp.Regex('[ ]{15}')
    field_empty.setParseAction(pp.replaceWith(''))
    av_number = av_number | field_empty
    av_number = av_number.setName('Audio-Visual Number') \
        .setResultsName('av_number')

    field = pp.Group(society_code + av_number)

    field.setParseAction(lambda v: _to_avi(v[0]))

    field = field.setName(name)

    return field.setResultsName('audio_visual_key')
开发者ID:clauxz,项目名称:CWR-DataApi,代码行数:31,代码来源:special.py


示例8: wrap_as_optional

    def wrap_as_optional(self, field, name, columns):
        """
        Adds a wrapper rule to the field to accept empty strings.

        This empty string should be of the same size as the columns parameter.
        One smaller or bigger will be rejected.

        This wrapper will return None if the field is empty.

        :param field: the field to wrap
        :param name: name of the field
        :param columns: number of columns it takes
        :return: the field with an additional rule to allow empty strings
        """
        # Regular expression accepting as many whitespaces as columns
        field_empty = pp.Regex('[ ]{' + str(columns) + '}')

        field_empty.setName(name)

        # Whitespaces are not removed
        field_empty.leaveWhitespace()

        # None is returned by this rule
        field_empty.setParseAction(pp.replaceWith(None))

        field_empty = field_empty.setResultsName(field.resultsName)

        field = field | field_empty

        field.setName(name)

        field.leaveWhitespace()

        return field
开发者ID:gitter-badger,项目名称:CWR-DataApi,代码行数:34,代码来源:adapter.py


示例9: Syntax

def Syntax():
    imp = Literal(u'⇒').setParseAction(replaceWith("Implies"))
    conj = Literal(u'∧').setParseAction(replaceWith("Conjunction"))
    disj = Literal(u'∨').setParseAction(replaceWith("Disjunction"))
    iff = Literal(u'⇔').setParseAction(replaceWith("Disjunction"))

    #op = oneOf(u'⇒ ∧')
    op = imp | conj | disj | iff
    lpar = Literal('(').suppress()
    rpar = Literal(')').suppress()
    neg = Literal(u'¬').setParseAction(replaceWith("Negation"))
    prop = Word(u"pqr")
    expr = Forward()
    atom = prop | Group(lpar + expr + rpar)
    expr << ((atom + ZeroOrMore(op + expr)) | Group(neg + expr))

    return expr
开发者ID:balajirrao,项目名称:PyChaitin,代码行数:17,代码来源:logical_axioms.py


示例10: 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


示例11: _make_valid_state_name

 def _make_valid_state_name(self, state_name):
     """Transform the input state_name into a valid state in XMLBIF.
     XMLBIF states must start with a letter an only contain letters,
     numbers and underscores.
     """
     s = str(state_name)
     s_fixed = pp.CharsNotIn(pp.alphanums + "_").setParseAction(pp.replaceWith("_")).transformString(s)
     if not s_fixed[0].isalpha():
         s_fixed = "state" + s_fixed
     return s_fixed
开发者ID:MariosRichards,项目名称:BES_analysis_code,代码行数:10,代码来源:XMLBIF.py


示例12: iswc

def iswc(name=None, compulsory=False):
    """
    ISWC field.

    A ISWC code written on a field follows the Pattern TNNNNNNNNNC. This being:
    - T: header, it is always T.
    - N: numeric value.
    - C: control digit.

    So, for example, an ISWC code field can contain T0345246801.

    :param name: name for the field
    :param compulsory: indicates if the empty string is disallowed
    :return: a parser for the ISWC field
    """

    if name is None:
        name = 'ISWC Field'

    # Header is always T
    header = pp.Literal('T').suppress()
    header = header.setName('ISWC Header').setResultsName('header')

    # ID code is composed of 9 numbers
    id_code = basic.numeric(9, compulsory=True)
    id_code = id_code.setName('ID Code').setResultsName('id_code')

    # Check digit is a single number
    check_digit = basic.numeric(1, compulsory=True)
    check_digit = check_digit.setName('Check Digit').setResultsName('check_digit')

    # T followed by 10 numbers
    field = pp.Group(header + id_code + check_digit)

    # Parse action
    field.setParseAction(lambda c: _to_iswccode(c[0]))

    # Name
    field.setName(name)

    if not compulsory:
        # If it is not compulsory then it can be set as empty
        empty = pp.Regex('[ ]{11}')
        empty.setParseAction(pp.replaceWith(None))
        empty.setName(name)

        field = empty | field
        # Name
        field.setName(name)

    # White spaces are not removed
    field.leaveWhitespace()

    return field.setResultsName('iswc')
开发者ID:toddrimes,项目名称:CWR-DataApi,代码行数:54,代码来源:special.py


示例13: convert_to_literal

        def convert_to_literal(tok, val):
            """
            Converts a value to pyparsing caselessliteral

            :param tok: the token we want to find/replace
            :type tok: str
            :param val: the integer the token represented
            :type val: int
            :return: pyparsing caseless literal
            :rtype: pyparsing.CaselessLiteral
            """
            return CaselessLiteral(tok) \
                .setName(tok) \
                .setParseAction(replaceWith(val))
开发者ID:SerenitySoftwareLLC,项目名称:cahoots,代码行数:14,代码来源:number.py


示例14: char_code

def char_code(columns, name=None, compulsory=False):
    """
    Character set code field.

    :param name: name for the field
    :param compulsory: indicates if the empty string is disallowed
    :return: an instance of the Character set code field rules
    """
    if name is None:
        name = 'Char Code Field (' + str(columns) + ' columns)'

    if columns <= 0:
        raise BaseException()

    char_sets = None
    for char_set in _tables.character_sets():
        regex = '[ ]{' + str(15 - len(char_set)) + '}' + char_set
        if char_sets is None:
            char_sets = regex
        else:
            char_sets += '|' + regex

    # Accepted sets
    _character_sets = pp.Regex(char_sets)
    _unicode_1_16b = pp.Regex('U\+0[0-8,A-F]{3}[ ]{' + str(columns - 6) + '}')
    _unicode_2_21b = pp.Regex('U\+0[0-8,A-F]{4}[ ]{' + str(columns - 7) + '}')

    # Basic field
    char_code_field = (_character_sets | _unicode_1_16b | _unicode_2_21b)

    # Parse action
    char_code_field = char_code_field.setParseAction(lambda s: s[0].strip())

    # Name
    char_code_field.setName(name)

    if not compulsory:
        char_code_field_empty = pp.Regex('[ ]{' + str(columns) + '}')
        char_code_field_empty.setName(name)

        char_code_field_empty.leaveWhitespace()

        char_code_field_empty.setParseAction(pp.replaceWith(None))

        char_code_field = char_code_field | char_code_field_empty

        char_code_field.setName(name)

    return char_code_field
开发者ID:toddrimes,项目名称:CWR-DataApi,代码行数:49,代码来源:table.py


示例15: __init__

    def __init__(self):

        # codec used for encoding of usermessages
        self.codec = lightpile.codec

        EOL = pp.LineEnd()
        SOL = pp.LineStart().leaveWhitespace()
        blankline = SOL + EOL
        comment = '#' + pp.restOfLine + EOL

        self.comment_stripper = comment.setParseAction(pp.replaceWith("\n"))
        self.blankline_stripper = blankline.setParseAction(pp.replaceWith(""))

        # filegrammar
        ws = ' \t'
        standard_chars = pp.printables.replace('#', '')
        text = pp.OneOrMore(pp.White(ws) |
                            pp.quotedString |
                            pp.Word(standard_chars))
        text.setParseAction(lambda tokens: ''.join(tokens))

        lbracket = pp.Literal("[").suppress()
        rbracket = pp.Literal("]").suppress()
        # identifiers have to start with a unicode-letter and can continue
        # with any number of unicode-letters or any of
        # ':', '%', '+', '-', '_', '.', ','
        self.identifier = pp.Regex(r'[^\W\d]([^\W]|[%:_,\+\-\.])*', re.U)
        sectionhead = (lbracket + self.identifier + rbracket +
                       EOL.suppress())
        sectionline = ~sectionhead + ~pp.StringEnd() + pp.restOfLine + EOL
        sectionlines = pp.ZeroOrMore(sectionline)
        sectionlines.setParseAction(lambda tokens: ''.join(tokens))

        self.filegrammar = pp.dictOf(sectionhead, sectionlines)

        self._init_sectiongrammars()
开发者ID:Ri-P,项目名称:Lightpile,代码行数:36,代码来源:parser.py


示例16: 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('pool type'), action=self._parse_setter(POOLTYPE))
        gr_line = gr_line | np(PList('maximum volumes'), action=self._parse_setter(MAXIMUMVOLUMES))
        gr_line = gr_line | np((STORAGE,), action=self._parse_setter(STORAGE))
        gr_line = gr_line | np(PList('use volume once'), gr_yn, action=self._parse_setter(USEVOLUMEONCE))
        gr_line = gr_line | np(PList('catalog files'), gr_yn, action=self._parse_setter(CATALOGFILES))
        gr_line = gr_line | np(PList('auto prune'), gr_yn, action=self._parse_setter(AUTOPRUNE))
        gr_line = gr_line | np((RECYCLE,), gr_yn, action=self._parse_setter(RECYCLE))
        gr_line = gr_line | np(PList('recycle oldest volume'), gr_yn, action=self._parse_setter(RECYCLEOLDESTVOLUME))
        gr_line = gr_line | np(PList('recycle current volume'), gr_yn, action=self._parse_setter(RECYCLECURRENTVOLUME))
        gr_line = gr_line | np(PList('purge oldest volume'), gr_yn, action=self._parse_setter(PURGEOLDESTVOLUME))
        gr_line = gr_line | np(PList('maximum volume jobs'), gr_number, action=self._parse_setter(MAXIMUMVOLUMEJOBS))
        gr_line = gr_line | np(PList('maximum volume files'), gr_number, action=self._parse_setter(MAXIMUMVOLUMEFILES))
        gr_line = gr_line | np(PList('maximum volume bytes'), action=self._parse_setter(MAXIMUMVOLUMEBYTES))
        gr_line = gr_line | np(PList('volume use duration'), action=self._parse_setter(VOLUMEUSEDURATION))
        gr_line = gr_line | np(PList('volume retention'), action=self._parse_setter(VOLUMERETENTION))
        gr_line = gr_line | np(PList('action on purge'), action=self._parse_setter(ACTIONONPURGE))
        gr_line = gr_line | np(PList('scratch pool'), action=self._parse_setter(SCRATCHPOOL))
        gr_line = gr_line | np(PList('recycle pool'), action=self._parse_setter(RECYCLEPOOL))
        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(PList('cleaning prefix'), action=self._parse_setter(CLEANINGPREFIX))
        gr_line = gr_line | np(PList('label format'), action=self._parse_setter(LABELFORMAT))

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


示例17: numeric

def numeric(columns, name=None, compulsory=False):
    """
    Creates the grammar for a Numeric (N) field, accepting only the specified number of characters.

    This version only allows integers.

    This can be a compulsory field, in which case the zero is disallowed.

    :param columns: number of columns for this field
    :param name: name for the field
    :param compulsory: indicates if the zero is disallowed
    :return: grammar for the integer numeric field
    """

    if name is None:
        name = 'Numeric Field'

    if columns <= 0:
        # Can't be empty or have negative size
        raise BaseException()

    # Only numbers are accepted
    field = pp.Regex('[0-9]{' + str(columns) + '}')

    # Parse action
    field.setParseAction(lambda n: _to_int(n))
    field.leaveWhitespace()

    # Name
    field.setName(name)

    if not compulsory:
        empty = pp.Regex('[ ]{' + str(columns) + '}')

        empty.setParseAction(pp.replaceWith(None))

        empty.setName(name)

        # White spaces are not removed
        empty.leaveWhitespace()

        field = field | empty

        # Name
        field.setName(name)

    return field
开发者ID:toddrimes,项目名称:CWR-DataApi,代码行数:47,代码来源:basic.py


示例18: remove_empty_statements

def remove_empty_statements(string, seperator=';'):
    """Remove empty statements from the string

    Args:
        string(str): String to be processed
        seperator(str): Seperater to be checked for duplicates

    Returns:
        result(str): String with empty statements trimmed
    """
    if string == '':
        return string

    empty_statement = seperator + OneOrMore(seperator)
    empty_statement.setParseAction(replaceWith(seperator))
    string = empty_statement.transformString(string)

    return string.lstrip(seperator)
开发者ID:abhishekmahawar,项目名称:dataduct,代码行数:18,代码来源:transform.py


示例19: visan

def visan(name=None, compulsory=False):
    """
    Creates the grammar for a V-ISAN code.

    This is a variation on the ISAN (International Standard Audiovisual Number)

    :param name: name for the field
    :param compulsory: indicates if the empty string is disallowed
    :return: grammar for an ISRC field
    """

    if name is None:
        name = 'V-ISAN Field'

    version = basic.numeric(8)
    version = version.setName('Version').setResultsName('version')

    isan = basic.numeric(12)
    isan = isan.setName('ISAN').setResultsName('isan')

    episode = basic.numeric(4)
    episode = episode.setName('Episode').setResultsName('episode')

    check_digit = basic.numeric(1)
    check_digit = check_digit.setName('Check Digit').setResultsName('check_digit')

    field = pp.Group(version + isan + episode + check_digit)

    field.setParseAction(lambda v: _to_visan(v[0]))

    field.setName(name)

    if not compulsory:
        # If it is not compulsory then it can be set as empty
        empty = pp.Regex('[ ]{25}')
        empty.setParseAction(pp.replaceWith(None))
        empty.setName(name)

        field = empty | field

        # Name
        field.setName(name)

    return field.setResultsName('visan')
开发者ID:toddrimes,项目名称:CWR-DataApi,代码行数:44,代码来源:special.py


示例20: lookup

def lookup(values, columns=1, name=None, compulsory=False):
    """
    Creates the grammar for a Lookup (L) field, accepting only values from a list.

    The 'columns' parameter is used only in the case the field is optional. It will be used to indicate the number
    of whitespaces this field can take.

    Like in the Alphanumeric field, the result will be stripped of all heading and trailing whitespaces.

    :param columns: number of columns, for the case this field is left empty
    :param name: name for the field
    :param compulsory: indicates if the empty string is disallowed
    :return: grammar for the lookup field
    """
    if name is None:
        name = 'Lookup Field'

    # Only the specified values are allowed
    lookup_field = pp.oneOf(values)

    lookup_field.setName(name)

    lookup_field.setParseAction(lambda s: s[0].strip())

    lookup_field.leaveWhitespace()

    if not compulsory:
        lookup_field_option = pp.Regex('[ ]{' + str(columns) + '}')

        lookup_field_option.setName(name)

        lookup_field_option.leaveWhitespace()

        lookup_field_option.setParseAction(pp.replaceWith(None))

        lookup_field = lookup_field | lookup_field_option

        lookup_field.setName(name)

        lookup_field.leaveWhitespace()

    return lookup_field
开发者ID:toddrimes,项目名称:CWR-DataApi,代码行数:42,代码来源:basic.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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