问题描述
我正在弄乱格式化并意识到正确的
对象可以很容易地告诉我对字符串%
映射的访问权限%映射操作。这是一个相当着名的
技术,经过修改后告诉我在格式使用的任何
映射中需要出现哪些键。
class一切:
def __init __(self,format ="%s",discover = False):
self.names = {}
self.values = []
self.format = format
self.discover = discover
def __getitem __( self,key):
x = self.format%key
if self.discover:
self.names [key] = self.names .get(key,0)+ 1
返回x
def nameList(个体经营):
if self.names:
返回["% - 20s%d" %i for i in self.names.items()]
else:
返回self.values
def __getattr __(self,name) :
打印属性,名称,请求
返回无
def __repr __(自我):
返回"<所有对象在0x%x>" %id(self)
def nameCount(模板):
et = Everything(discover = True)
p = template% et b / b $ b nlst = et.nameList()
nlst.sort()
返回nlst
为nameCount中的s("%(name)s%(value)s%(name)s"):
print s
结果这项工作的成果是:
名称2
价值1
我一直在想它是否'可以在非映射类型格式字符串上执行类似的分析
,以便了解
提供的元组有多长,或者我是否会被迫对形式字符串进行词法分析。
问候
史蒂夫
-
Steve Holden +1 703 861 4237 +1 800 494 3119
Holden Web LLC
Python网页编程
当我使用formatstring%mapping时,我认为如果你能得到完整的话,它可以是有用的格式说明符信息自己做
完整格式化,即使对于发明的格式说明符也是如此。如果str .__ mod__在另一个map-or-tuple-object上查找
a __format__方法,则可以在不破坏向后兼容性的情况下完成这个
。如果找到了,
就会调用这个方法,这个方法可以预期
def __format __(self,
ix,#index from 0计算每%...格式
名称,#来自%(名称)或''''
宽度,#来自%width.prec
prec,#ditto
fc,#格式字符F in%(x)F
all#只是%之间的任何副本,包括F
):...
这显然可以让你根据需要处理非映射等等。
最受欢迎的用途可能是拦截宽度%(名称)< width> s
并为对象进行自定义格式化(例如居中于可用空间)
并返回正确大小的字符串。
因为ix是一个整数并且没有正常的
元组而无法找到正确的对象,你可以给你的格式化对象'__init__方法关键字参数
指定匿名slo的参数在格式字符串中的ts,通常
将它们命名为a0,a1,a2等。然后当你得到一个没有名字的ix时,你可以
写self.kw.得到(''%as''%ix)来获取值,就像在使用中一样使用
''%(name)s%s''%Formatter(a1 = thevalue)#Formatterter as base class知道如何进行姓名查询
或者这只是想法吗?
问候,
Bengt Richter
stringobject.c中的PyString_Format()确定元组长度,然后开始
格式化过程,最后检查是否所有项目都被使用 - 所以
不,它''不可能像你一样给它调整一个(自动增长的)元组
用字典做了。
这里的蛮力相当于nameCount(),灵感来自Hans的帖子
Nowak(。
def countArgs(格式):
args =(1,)*(format.count("%") - 2 * format.count("%) %"))
而True:
尝试:
格式%args
除了TypeError,e:
args + =(1,)
else:
返回len(args)
samples = [
(",0),
(" %%",0),
(" %s",1),
(" %%% s",1),
(" %%% *。* d",3),
(" %%%%% * s",2),
("%s%* s%* d%* f",7)]
表示样本中的f,n:
f%((1,)* n)
断言countArgs(f)== n
未经测试超出您所看到的范围。
Peter
我刚试了一个实验,但这似乎不太可能。
问题似乎是它希望参数以元组的形式为
,如果你给它别的东西,
它将它包装在一个单元组元组中并使用它。
这似乎发生在一个自定义的元组子类,
所以它必须是做一个确切的类型检查。
所以看起来你必须解析格式字符串。
-
Greg Ewing,计算机科学系,
坎特伯雷大学,
新西兰基督城
I was messing about with formatting and realized that the right kind of
object could quite easily tell me exactly what accesses are made to the
mapping in a string % mapping operation. This is a fairly well-known
technique, modified to tell me what keys would need to be present in any
mapping used with the format.
class Everything:
def __init__(self, format="%s", discover=False):
self.names = {}
self.values = []
self.format=format
self.discover = discover
def __getitem__(self, key):
x = self.format % key
if self.discover:
self.names[key] = self.names.get(key, 0) + 1
return x
def nameList(self):
if self.names:
return ["%-20s %d" % i for i in self.names.items()]
else:
return self.values
def __getattr__(self, name):
print "Attribute", name, "requested"
return None
def __repr__(self):
return "<Everything object at 0x%x>" % id(self)
def nameCount(template):
et = Everything(discover=True)
p = template % et
nlst = et.nameList()
nlst.sort()
return nlst
for s in nameCount("%(name)s %(value)s %(name)s"):
print s
The result of this effort is:
name 2
value 1
I''ve been wondering whether it''s possible to perform a similar analysis
on non-mapping-type format strings, so as to know how long a tuple to
provide, or whether I''d be forced to lexical analysis of the form string.
regards
Steve
--
Steve Holden +1 703 861 4237 +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/
Python Web Programming http://pydish.holdenweb.com/
When I was playing with formatstring % mapping I thought it could
be useful if you could get the full format specifier info an do your own
complete formatting, even for invented format specifiers. This could be
done without breaking backwards compatibility if str.__mod__ looked for
a __format__ method on the other-wise-mapping-or-tuple-object. If found,
it would call the method, which would expect
def __format__(self,
ix, # index from 0 counting every %... format
name, # from %(name) or ''''
width, # from %width.prec
prec, # ditto
fc, # the format character F in %(x)F
all # just a copy of whatever is between % and including F
): ...
This would obviously let you handle non-mapping as you want, and more.
The most popular use would probably be intercepting width in %(name)<width>s
and doing custom formatting (e.g. centering in available space) for the object
and returning the right size string.
Since ix is an integer and doesn''t help find the right object without the normal
tuple, you could give your formatting object''s __init__ method keyword arguments
to specify arguments for anonymous slots in the format string, conventionally
naming them a0, a1, a2 etc. Then later when you get an ix with no name, you could
write self.kw.get(''%as''%ix) to get the value, as in use like
''%(name)s %s'' % Formatter(a1=thevalue) # Formatter as base class knows how to do name lookup
Or is this just idearrhea?
Regards,
Bengt Richter
PyString_Format() in stringobject.c determines the tuple length, then starts
the formatting process and finally checks whether all items were used -- so
no, it''s not possible to feed it a tweaked (auto-growing) tuple like you
did with the dictionary.
Here''s a brute-force equivalent to nameCount(), inspired by a post by Hans
Nowak (http://mail.python.org/pipermail/pyt...y/230392.html).
def countArgs(format):
args = (1,) * (format.count("%") - 2*format.count("%%"))
while True:
try:
format % args
except TypeError, e:
args += (1,)
else:
return len(args)
samples = [
("", 0),
("%%", 0),
("%s", 1),
("%%%s", 1),
("%%%*.*d", 3),
("%%%%%*s", 2),
("%s %*s %*d %*f", 7)]
for f, n in samples:
f % ((1,)*n)
assert countArgs(f) == n
Not tested beyond what you see.
Peter
I just tried an experiment, and it doesn''t seem to be possible.
The problem seems to be that it expects the arguments to be
in the form of a tuple, and if you give it something else,
it wraps it up in a 1-element tuple and uses that instead.
This seems to happen even with a custom subclass of tuple,
so it must be doing an exact type check.
So it looks like you''ll have to parse the format string.
--
Greg Ewing, Computer Science Dept,
University of Canterbury,
Christchurch, New Zealand
http://www.cosc.canterbury.ac.nz/~greg
这篇关于枚举格式化字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!