[译]The Python Tutorial#Brief Tour of the Standard Library — Part II
第二部分介绍更多满足专业编程需求的高级模块,这些模块在小型脚本中很少用到。
reprlib
模块为大型或者深度嵌套的容器提供了一个定制版本的repr()
函数:
>>> import reprlib
>>> reprlib.repr(set('supercalifragilisticexpialidocious'))
"{'a', 'c', 'd', 'e', 'f', 'g', ...}"
pprint
模块为内嵌对象或者用户自定义对象以解释器可读方式打印提供了更精细的控制。当打印结果超过一行时,“打印美化器”添加换行符和缩进,清晰显示原有的数据结构:
>>> import pprint
>>> t = [[[['black', 'cyan'], 'white', ['green', 'red']], [['magenta',
... 'yellow'], 'blue']]]
...
>>> pprint.pprint(t, width=30)
[[[['black', 'cyan'],
'white',
['green', 'red']],
[['magenta', 'yellow'],
'blue']]]
textwrap
模块格式化文本段落适应指定屏幕宽度:
>>> import textwrap
>>> doc = """The wrap() method is just like fill() except that it returns
... a list of strings instead of one big string with newlines to separate
... the wrapped lines."""
...
>>> print(textwrap.fill(doc, width=40))
The wrap() method is just like fill()
except that it returns a list of strings
instead of one big string with newlines
to separate the wrapped lines.
local
模块访问特定文化数据格式的数据库。区域设置格式函数的分组属性提供了使用组分隔符格式化数字的直接方法:
>>> import locale
>>> locale.setlocale(locale.LC_ALL, 'English_United States.1252')
'English_United States.1252'
>>> conv = locale.localeconv() # get a mapping of conventions
>>> x = 1234567.8
>>> locale.format("%d", x, grouping=True)
'1,234,567'
>>> locale.format_string("%s%.*f", (conv['currency_symbol'],
... conv['frac_digits'], x), grouping=True)
'$1,234,567.80'
11.2 Templting
string
模块包括一个功能强大的Template
类,其简化的语法适用于最终用户的编辑。该类允许用户自定义他们的应用,而不用修改应用。
格式化使用由$
和有效Python标识符(字母数字字符以及下划线)组成的占位符。占位符外围的花括号允许其后跟更多数字字母字符而无需中间空格。使用$$
转义$
:
>>> from string import Template
>>> t = Template('${village}folk send $$10 to $cause.')
>>> t.substitute(village='Nottingham', cause='the ditch fund')
'Nottinghamfolk send $10 to the ditch fund.'
当参数字典或者关键字参数没有提供对应的占位符时,substitute()
方法抛出KeyError异常。对于邮件合并风格的应用程序,用户提供的数据可能不完全,使用safe_substitute()
方法更加合适——该方法会保留为匹配的占位符不变:
>>> t = Template('Return the $item to $owner.')
>>> d = dict(item='unladen swallow')
>>> t.substitute(d)
Traceback (most recent call last):
...
KeyError: 'owner'
>>> t.safe_substitute(d)
'Return the unladen swallow to $owner.'
Template的子类可以指定自定义的定界符。例如,图片浏览器的批量重命名工具可能使用百分比号作为占位符,如当前日期,图片序列码或者文件格式:
>>> import time, os.path
>>> photofiles = ['img_1074.jpg', 'img_1076.jpg', 'img_1077.jpg']
>>> class BatchRename(Template):
... delimiter = '%'
>>> fmt = input('Enter rename style (%d-date %n-seqnum %f-format): ')
Enter rename style (%d-date %n-seqnum %f-format): Ashley_%n%f
>>> t = BatchRename(fmt)
>>> date = time.strftime('%d%b%y')
>>> for i, filename in enumerate(photofiles):
... base, ext = os.path.splitext(filename)
... newname = t.substitute(d=date, n=i, f=ext)
... print('{0} --> {1}'.format(filename, newname))
img_1074.jpg --> Ashley_0.jpg
img_1076.jpg --> Ashley_1.jpg
img_1077.jpg --> Ashley_2.jpg
模板的另一种应用是将程序逻辑与多种输出格式的细节分开。这样使得自定义模板替换为XML文件,纯文本报告