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


Python string.Formatter类代码示例

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


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

示例1: parse_route_path

def parse_route_path(path):
    fmt = Formatter()

    rule = turn_noncapturing(path)

    arguments = OrderedDict()
    pattern = ''
    for literal_text, field_name, format_spec, conversion in fmt.parse(rule):
        pattern += literal_text
        if field_name is None:
            continue

        format_spec = format_spec.lower()
        subpattern = _route_rule_types.get(format_spec, None)
        if subpattern is None:
            subpattern = _route_rule_types.get('str')

        if field_name in arguments:
            err = "The argument \{%s:%s\} are already defined in %s"
            err %= (field_name, format_spec, path)
            raise SyntaxError(err)

        arguments[field_name] = format_spec

        pattern += '(?P<' + field_name + '>' + subpattern + ')'

    return pattern, arguments
开发者ID:brandonDu,项目名称:domainics,代码行数:27,代码来源:route_path.py

示例2: get_format_args

def get_format_args(fstr):
    # TODO: memoize
    formatter = Formatter()
    fargs, fkwargs, _dedup = [], [], set()

    def _add_arg(argname, type_char='s'):
        if argname not in _dedup:
            _dedup.add(argname)
            argtype = _TYPE_MAP.get(type_char, str)  # TODO: unicode
            try:
                fargs.append((int(argname), argtype))
            except ValueError:
                fkwargs.append((argname, argtype))

    for lit, fname, fspec, conv in formatter.parse(fstr):
        if fname is not None:
            type_char = fspec[-1:]
            fname_list = re.split('[.[]', fname)
            if len(fname_list) > 1:
                raise ValueError('encountered compound format arg: %r' % fname)
            try:
                base_fname = fname_list[0]
                assert base_fname
            except (IndexError, AssertionError):
                raise ValueError('encountered anonymous positional argument')
            _add_arg(fname, type_char)
            for sublit, subfname, _, _ in formatter.parse(fspec):
                # TODO: positional and anon args not allowed here.
                if subfname is not None:
                    _add_arg(subfname)
    return fargs, fkwargs
开发者ID:justinvanwinkle,项目名称:boltons,代码行数:31,代码来源:formatutils.py

示例3: parse_pattern

def parse_pattern(format_string, env, wrapper=lambda x, y: y):
    """ Parse the format_string and return prepared data according to the env.

    Pick each field found in the format_string from the env(ironment), apply
    the wrapper on each data and return a mapping between field-to-replace and
    values for each.
    """

    formatter = Formatter()
    fields = [x[1] for x in formatter.parse(format_string) if x[1] is not None]

    prepared_env = {}

    # Create a prepared environment with only used fields, all as list:
    for field in fields:
        # Search for a movie attribute for each alternative field separated
        # by a pipe sign:
        for field_alt in (x.strip() for x in field.split('|')):
            # Handle default values (enclosed by quotes):
            if field_alt[0] in '\'"' and field_alt[-1] in '\'"':
                field_values = field_alt[1:-1]
            else:
                field_values = env.get(field_alt)
            if field_values is not None:
                break
        else:
            field_values = []
        if not isinstance(field_values, list):
            field_values = [field_values]
        prepared_env[field] = wrapper(field_alt, field_values)

    return prepared_env
开发者ID:NaPs,项目名称:Kolekto,代码行数:32,代码来源:pattern.py

示例4: get_value

	def get_value(self, key, args, kwds):
        	# Let default get_value() handle ints
		if not isinstance(key, str):
                        return Formatter.get_value(self, key, args, kwds)

		# HACK, we allow defining strings via fields to allow
                # conversions
                if key[:2] == 's|':
                        return key[2:]

		if key[:2] == 't|':
                        # title mode ("TITLE ATTR")
                        include_title = True
                elif key[:2] == 'a|':
                	# plain attribute mode ("ATTR")
                	include_title = False
                else:
                        # No special field, have default get_value() get it
                        return Formatter.get_value(self, key, args, kwds)

		key = key[2:]
                (title, value) = self._nlattr(key)

                if include_title:
                        if not title:
                                title = key	# fall back to key as title
                        value = kw(title) + ' ' + value

                return value
开发者ID:BorodaZizitopa,项目名称:libnl,代码行数:29,代码来源:util.py

示例5: select

    def select(self,type='VAV',subtype = ['RM STPT DIAL','ROOM TEMP'], floor = 0,nexp='', pattern ='{i}',cond = 'cmax(x,7)',maxn = 10, dtfilter = ''):
        env = self._genv()       
        env.init()
        l = env.getSensorsByType(type)
        lname = []

        for it in l:
            k = it.split(':')
            if floor != 0:
                fl = int(k[0].split('.')[1])
                if fl != floor:
                    continue

                if nexp != '':
                    sname = k[0].split('.')[3]
                    if not fnmatch.fnmatch(sname,nexp):
                        continue    

                if k[1] in subtype:
                    lname.append((it,env.getSensorId(it)))

        ltemp = sorted(lname,key=itemgetter(0))[:maxn]
        filt = ''
        i = 0

        f = Formatter()
        l = "{{%s}}"
        f.format(l)

        ns = ''
        exp = []
        i,m =0,len(ltemp)
        loopi=0
        while i < m:
            h = f.parse(pattern)
            for a,b,c,d in h :
                ns += a 
                if b is not None : 
                    ns += '{' + str(eval(b)) + '}'
                    i = eval(b)
                    loopi = max(i,loopi)
            if cond != '':
                ns += '.apply(lambda x:' + cond + ')'
            if loopi < m-1:
                ns += '; '
            i = loopi + 1

        cs = self.getSeries(ltemp,dtfilter)
        re = self.getExpression(ltemp,ns, cs)
        series = []
        for name ,c in re:
            dataserie = defaultdict()  
            json_s = c[['stime','svalue']].to_json(orient='values')
            dataserie['name']=name
            dataserie['data']=json_s
            series.append(dataserie)
        return series
开发者ID:QuicNYC,项目名称:rscript,代码行数:57,代码来源:graph.py

示例6: get_value

 def get_value(self, key, args, kwargs):
     if '|' in key:
         for kk in key.split('|'):
             out = Formatter.get_value(self, kk, args, kwargs)
             if out is not None and len(out) > 0:
                 return out
     out = Formatter.get_value(self, key, args, kwargs)
     if failOnEmpty and (out is None or len(out) == 0):
         raise ValueError("Cannot resolve %s" % key)
     return out
开发者ID:essembeh,项目名称:script-utils,代码行数:10,代码来源:plooze.py

示例7: strfdelta

def strfdelta(tdelta, fmt):
    """ Get a string from a timedelta.
    """
    f, d = Formatter(), {}
    l = {'D': 86400, 'H': 3600, 'M': 60, 'S': 1}
    k = list(map(lambda x: x[1], list(f.parse(fmt))))
    rem = int(tdelta.total_seconds())
    for i in ('D', 'H', 'M', 'S'):
        if i in k and i in l.keys():
            d[i], rem = divmod(rem, l[i])
    return f.format(fmt, **d)
开发者ID:restudToolbox,项目名称:package,代码行数:11,代码来源:auxiliary_shared.py

示例8: pformat

def pformat(temp, **fmt):
    """Format a template string partially.

    Examples
    --------
    >>> pformat("{a}_{b}", a='x')
    'x_{b}'
    """
    formatter = Formatter()
    mapping = _FormatDict(fmt)
    return formatter.vformat(temp, (), mapping)
开发者ID:adykstra,项目名称:mne-python,代码行数:11,代码来源:misc.py

示例9: tokenize_format_str

def tokenize_format_str(fstr, resolve_pos=True):
    ret = []
    if resolve_pos:
        fstr = infer_positional_format_args(fstr)
    formatter = Formatter()
    for lit, fname, fspec, conv in formatter.parse(fstr):
        if lit:
            ret.append(lit)
        if fname is None:
            continue
        ret.append(BaseFormatField(fname, fspec, conv))
    return ret
开发者ID:justinvanwinkle,项目名称:boltons,代码行数:12,代码来源:formatutils.py

示例10: make_tag

def make_tag():
    today = datetime.datetime.today()
    date = today.strftime(date_format)
    print(date)
    seq=1
    "git tag --list=release/%s/*" % date
    values={
        "date": date,
        "sequence": seq
    }
    formatter = Formatter()
    tag = formatter.vformat(tag_format, [], values)
    print(tag)
开发者ID:wikimedia,项目名称:phabricator-deployment,代码行数:13,代码来源:tags.py

示例11: get_field

 def get_field(self, field_name, args, kwargs):
     if self.expand == StringFormatType.error:
         return Formatter.get_field(self, field_name, args, kwargs)
     try:
         return Formatter.get_field(self, field_name, args, kwargs)
     except (AttributeError, KeyError, TypeError):
         reg = re.compile("[^\.\[]+")
         try:
             key = reg.match(field_name).group()
         except:
             key = field_name
         if self.expand == StringFormatType.empty:
             return ('', key)
         else:  # StringFormatType.unchanged
             return ("{%s}" % field_name, key)
开发者ID:foutoucour,项目名称:rez,代码行数:15,代码来源:formatting.py

示例12: save_params

    def save_params(self):
        f = Formatter()
        tokens = f.parse(self.command_string)

        params = []
        for (_ , param_name, _ , _) in tokens:
            if param_name is not None:
                if param_name in self.inputdict:
                    param = self.inputdict[param_name]
                else:
                    param = iobjs.Input(name=param_name)
                if param_name in self._defaults:
                    param.default = self._defaults[param_name]
                params += [param]
        self.inputs = params
开发者ID:Zaharid,项目名称:labcore,代码行数:15,代码来源:models.py

示例13: vformat

 def vformat(self, format_string, args, kwargs):
     self.unused_args = {}
     ret = Formatter.vformat(self, format_string, args, kwargs)
     if not self.unused_args:
         return ret
     extra_data =  ', '.join('{0}={1}'.format(*kv) for kv in self.unused_args.items())
     return '{0} ({1})'.format(ret, extra_data)
开发者ID:imankulov,项目名称:tagged-logger,代码行数:7,代码来源:__init__.py

示例14: vformat

    def vformat(self, format_string, args, kwargs):
        matcher = re.compile(self._expr, re.VERBOSE)

        # special case of returning the object if the entire string
        # matches a single parameter
        try:
            result = re.match('^%s$' % self._expr, format_string, re.VERBOSE)
        except TypeError:
            return format_string.format(**kwargs)
        if result is not None:
            try:
                return kwargs[result.group("key")]
            except KeyError:
                pass

        # handle multiple fields within string via a callback to re.sub()
        def re_replace(match):
            key = match.group("key")
            default = match.group("default")

            if default is not None:
                if key not in kwargs:
                    return default
                else:
                    return "{%s}" % key
            return match.group(0)

        format_string = matcher.sub(re_replace, format_string)

        return Formatter.vformat(self, format_string, args, kwargs)
开发者ID:openstack-infra,项目名称:jenkins-job-builder,代码行数:30,代码来源:formatter.py

示例15: SafeStringParse

def SafeStringParse(formatter, s, keys):
    """
    A "safe" version :func:`string.Formatter.parse` that will 
    only parse the input keys specified in ``keys``
    
    Parameters
    ----------
    formatter : string.Formatter
        the string formatter class instance
    s : str
        the string we are formatting
    keys : list of str
        list of the keys to accept as valid
    """
    # the default list of keys
    l = list(Formatter.parse(formatter, s))
    
    toret = []
    for x in l:
        if x[1] in keys:
            toret.append(x)
        else:
            val = x[0]
            if x[1] is not None:
                fmt = "" if not x[2] else ":%s" %x[2]
                val += "{%s%s}" %(x[1], fmt)
            toret.append((val, None, None, None))
    return iter(toret)
开发者ID:rainwoodman,项目名称:nbodykit,代码行数:28,代码来源:nbkit-batch.py


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