本文整理汇总了Python中string.Formatter.parse方法的典型用法代码示例。如果您正苦于以下问题:Python Formatter.parse方法的具体用法?Python Formatter.parse怎么用?Python Formatter.parse使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类string.Formatter
的用法示例。
在下文中一共展示了Formatter.parse方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_format_args
# 需要导入模块: from string import Formatter [as 别名]
# 或者: from string.Formatter import parse [as 别名]
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
示例2: parse_route_path
# 需要导入模块: from string import Formatter [as 别名]
# 或者: from string.Formatter import parse [as 别名]
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
示例3: SafeStringParse
# 需要导入模块: from string import Formatter [as 别名]
# 或者: from string.Formatter import parse [as 别名]
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)
示例4: parse_pattern
# 需要导入模块: from string import Formatter [as 别名]
# 或者: from string.Formatter import parse [as 别名]
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
示例5: get_format_args
# 需要导入模块: from string import Formatter [as 别名]
# 或者: from string.Formatter import parse [as 别名]
def get_format_args(fstr):
"""
Turn a format string into two lists of arguments referenced by the
format string. One is positional arguments, and the other is named
arguments. Each element of the list includes the name and the
nominal type of the field.
# >>> get_format_args("{noun} is {1:d} years old{punct}")
# ([(1, <type 'int'>)], [('noun', <type 'str'>), ('punct', <type 'str'>)])
# XXX: Py3k
>>> get_format_args("{noun} is {1:d} years old{punct}") == \
([(1, int)], [('noun', str), ('punct', str)])
True
"""
# 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
示例6: select
# 需要导入模块: from string import Formatter [as 别名]
# 或者: from string.Formatter import parse [as 别名]
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
示例7: strfdelta
# 需要导入模块: from string import Formatter [as 别名]
# 或者: from string.Formatter import parse [as 别名]
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)
示例8: tokenize_format_str
# 需要导入模块: from string import Formatter [as 别名]
# 或者: from string.Formatter import parse [as 别名]
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
示例9: parse
# 需要导入模块: from string import Formatter [as 别名]
# 或者: from string.Formatter import parse [as 别名]
def parse(self, fmt_string):
for literal_txt, field_name, format_spec, conversion \
in Formatter.parse(self, fmt_string):
# Find $foo patterns in the literal text.
continue_from = 0
for m in self._dollar_pattern.finditer(literal_txt):
new_txt, new_field = m.group(1,2)
yield (new_txt, new_field, "", None)
continue_from = m.end()
# Re-yield the {foo} style pattern
yield (literal_txt[continue_from:], field_name, format_spec, conversion)
示例10: save_params
# 需要导入模块: from string import Formatter [as 别名]
# 或者: from string.Formatter import parse [as 别名]
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
示例11: strfdelta
# 需要导入模块: from string import Formatter [as 别名]
# 或者: from string.Formatter import parse [as 别名]
def strfdelta(tdelta, fmt='{D:02}d {H:02}h {M:02}m {S:02}s', inputtype='timedelta'):
"""Convert a datetime.timedelta object or a regular number to a custom-
formatted string, just like the stftime() method does for datetime.datetime
objects.
The fmt argument allows custom formatting to be specified. Fields can
include seconds, minutes, hours, days, and weeks. Each field is optional.
Some examples:
'{D:02}d {H:02}h {M:02}m {S:02}s' --> '05d 08h 04m 02s' (default)
'{W}w {D}d {H}:{M:02}:{S:02}' --> '4w 5d 8:04:02'
'{D:2}d {H:2}:{M:02}:{S:02}' --> ' 5d 8:04:02'
'{H}h {S}s' --> '72h 800s'
The inputtype argument allows tdelta to be a regular number instead of the
default, which is a datetime.timedelta object. Valid inputtype strings:
's', 'seconds',
'm', 'minutes',
'h', 'hours',
'd', 'days',
'w', 'weeks'
"""
# Convert tdelta to integer seconds.
if inputtype == 'timedelta':
remainder = int(tdelta.total_seconds())
elif inputtype in ['s', 'seconds']:
remainder = int(tdelta)
elif inputtype in ['m', 'minutes']:
remainder = int(tdelta)*60
elif inputtype in ['h', 'hours']:
remainder = int(tdelta)*3600
elif inputtype in ['d', 'days']:
remainder = int(tdelta)*86400
elif inputtype in ['w', 'weeks']:
remainder = int(tdelta)*604800
f = Formatter()
desired_fields = [field_tuple[1] for field_tuple in f.parse(fmt)]
possible_fields = ('W', 'D', 'H', 'M', 'S')
constants = {'W': 604800, 'D': 86400, 'H': 3600, 'M': 60, 'S': 1}
values = {}
for field in possible_fields:
if field in desired_fields and field in constants:
values[field], remainder = divmod(remainder, constants[field])
return f.format(fmt, **values)
示例12: _wrapped
# 需要导入模块: from string import Formatter [as 别名]
# 或者: from string.Formatter import parse [as 别名]
def _wrapped(pseudo_type, string, **kwargs):
text = []
formatter = Formatter()
for (literal_text, field_name, format_spec, conversion) in formatter.parse(string):
if literal_text:
literal_text = next_splitter_or_func(
literal_text, self.splitters, func, pseudo_type)
literal_text = literal_text.replace('{', '{{').replace('}', '}}')
text.append(literal_text)
if field_name is not None:
fmt = field_name
if conversion is not None:
fmt += '!' + conversion
if format_spec:
fmt += ':' + format_spec
text.append('{%s}' % (fmt, ))
return "".join(text)
示例13: strfdelta
# 需要导入模块: from string import Formatter [as 别名]
# 或者: from string.Formatter import parse [as 别名]
def strfdelta(tdelta, fmt=None):
from string import Formatter
if not fmt:
# The standard, most human readable format.
fmt = "{D} days {H:02} hours {M:02} minutes {S:02} seconds"
if tdelta == timedelta():
return "0 minutes"
formatter = Formatter()
return_map = {}
div_by_map = {'D': 86400, 'H': 3600, 'M': 60, 'S': 1}
keys = map(lambda x: x[1], list(formatter.parse(fmt)))
remainder = int(tdelta.total_seconds())
for unit in ('D', 'H', 'M', 'S'):
if unit in keys and unit in div_by_map.keys():
return_map[unit], remainder = divmod(remainder, div_by_map[unit])
return formatter.format(fmt, **return_map)
示例14: get_params
# 需要导入模块: from string import Formatter [as 别名]
# 或者: from string.Formatter import parse [as 别名]
def get_params(self):
formatter = Formatter()
format_iterator = formatter.parse(self.get_cleaned_content())
params = {
'args': list(),
'kwargs': set()
}
for _tuple in format_iterator:
field_name = _tuple[1]
if field_name is not None:
if field_name == '':
params['args'].append(field_name)
elif field_name.isdigit():
if field_name not in params['args']:
params['args'].append(field_name)
else:
params['kwargs'].add(field_name)
return params
示例15: parse
# 需要导入模块: from string import Formatter [as 别名]
# 或者: from string.Formatter import parse [as 别名]
def parse(self, fmt_string):
for literal_txt, field_name, format_spec, conversion in Formatter.parse(self, fmt_string):
# Find $foo patterns in the literal text.
continue_from = 0
txt = ""
for m in self._dollar_pattern.finditer(literal_txt):
new_txt, new_field = m.group(1, 2)
# $$foo --> $foo
if new_field.startswith("$"):
txt += new_txt + new_field
else:
yield (txt + new_txt, new_field, "", None)
txt = ""
continue_from = m.end()
# Re-yield the {foo} style pattern
yield (txt + literal_txt[continue_from:], field_name, format_spec, conversion)