格式化输出
- reprlib 库用来格式化
>>> import reprlib
>>> reprlib.repr(set('aabbccddeeeff'))
"{'a', 'b', 'c', 'd', 'e', 'f'}"
>>>
- 对集合能排序
>>> reprlib.repr(set('fdajfejaa'))
"{'a', 'd', 'e', 'f', 'j'}"
>>>
- pprint库用来缩进和空行,输出的内置对象和用户自定义对象能被解释器直接读取。
>>> p = [[['red', 'yellow'], ['pink']], ['black'], 'blue']
>>> pprint.pprint(p, width=5)
[[['red','yellow'],['pink']],['black'],'blue']
>>>
- textwrap用来格式化段落
>>> import textwrap as tw
>>> doc = ''' she is so gorgeous! I really like her !
... May the distance between her want and I am weak .
... Try Hard... Learning your all time... aseert...'''
>>> print(tw.fill(doc, width=40)) # 每行40个字母she is so gorgeous! I really like her !
May the distance between her want and I
am weak . Try Hard... Learning
your all time... aseert...
>>>
- Locale 模块处理与特定地域相关的数据格式。
>>> import locale
>>> locale.setlocale(locale.LC_ALL, 'English_United States.1252')
'English_United States.1252'
>>>
>>> conv = locale.localeconv()
>>> conv
{'int_curr_symbol': 'USD', 'currency_symbol': '$', 'mon_decimal_point': '.', 'mon_thousands_sep': ',', 'mon_grouping': [3, 0], 'positive_sign': '', 'negative_sign': '-', 'int_frac_digits': 2, 'frac_digits': 2, 'p_cs_precedes': 1, 'p_sep_by_space': 0, 'n_cs_precedes': 1, 'n_sep_by_space': 0, 'p_sign_posn': 3, 'n_sign_posn': 0, 'decimal_point': '.', 'thousands_sep': ',', 'grouping': [3, 0]}
>>>
>>> x = 12345.6
>>> locale.format_string("%d", x, grouping =True) # 对数字进行分隔
'12,345'
>>> locale.format_string("%s%*.f", (conv['currency_symbol'], conv['frac_digits'], x), grouping=True)
'$12,346'
模块
-
string模块的Template 类
用于格式化的 占位符($(字母,数字,下划线)) $ + 标识符 , 如果在外面加上{} 后面可直接跟字母,数字(不用空格)。
T = Template('${k}like $kk')
T.substitute(k='', kk='')
>>> from string import Template # 导入摸板>>> t = Template('${she} is so $how') # $加标识符表示占位>>> t.substitute(she='she', how='adorable') # 把占位符给替换了'she is so adorable'>>># 如果,参数不完整>>> t = Template('return the $item to $owner')>>> t.substitute(dict(item='unladen swallow')) # 未提供 owner的参数Traceback (most recent call last):File "<stdin>", line 1, in <module>File "D:\softWare\python\python3.7\lib\string.py", line 132, in substitutereturn self.pattern.sub(convert, self.template)File "D:\softWare\python\python3.7\lib\string.py", line 125, in convertreturn str(mapping[named])KeyError: 'owner'>>># 用户也可能出现上面滴参数不完整情况 用safe_substitute>>> t.safe_substitute(dict(item='unladen swallow'))'return the unladen swallow to $owner'>>>
- 对浏览器照片重命名
>>> import time, os.path>>> photofiles = ['img_102.jpg', 'img_104.jpg', 'img_106.jpg']>>> class BatchRename(Template): # 继承模板类... delimiter = '%'...>>> fmt = input('输入重命名的样式(%d-date %n-sequm %f-format): ')输入重命名的样式(%d-date %n-sequm %f-format): lel_%n%f>>> fmt'lel_%n%f'>>> br = BatchRename(fmt)>>> date = time.strftime('%d%b%y')>>> date'13May20'>>> for i, filename in enumerate(photofiles):... base, ext = os.path.splitext(filename)... newname = br.substitute(d=date, n=i, f=ext)... print('{0} --> {1}'.format(filename, newname))...img_102.jpg --> lel_0.jpgimg_104.jpg --> lel_1.jpgimg_106.jpg --> lel_2.jpg>>>
多线程
- 线程是一种对于非顺序依赖的多个任务进行解耦的技术。
- 多线程可以提高应用的响应效率 当接收用户输入的同时,保持其他任务在后台运行。
- 应用场景,将i/o 和 计算运行在两个并行的线程中。
import zipfile, threadingclass AsyncZip(threading.Thread):def __init__(self, infile, outfile): # 构造输入输出文件threading.Thread.__init__(self)self.infile = infileself.outfile = outfiledef run(self):f = zipfile.ZipFile(self.outfile, 'w', zipfile.ZIP_DEFLATED) # 打开文件只写f.write(self.infile) # 压缩文件f.close()print('完成后台压缩...', self.infile)# 测试
background = AsyncZip('e:/MyStudy/bitQianBlog/python/pythonBasic/StandLib/test.txt', 'output.zip')
background.start()print('主程序后台运行中...')background.join() # 等待后台任务完成...print('主程序一直等待后台任务完成...')
- 日志记录 – logging模块
>>> import logging as log # 日志记录模块
>>> log.debug('解决bug信息...')
>>> log.info('消息')
>>> log.warning('警告, 配置文件%s找不到', 'server.conf')
WARNING:root:警告, 配置文件server.conf找不到
>>> log.error('存在错误')
ERROR:root:存在错误
>>> log.critical('判定错误 -- 关机')
CRITICAL:root:判定错误 -- 关机
>>>
弱引用weakdef
- py 会自动进行内存管理(garbage collection)。
- 当某个对象的最后一个引用被移除后 不久就会释放所占的内存。
- weakdef 可以不创建引用,就可跟踪其它对象。
- 当对象不再需要时,它将自动从一个弱引用表中被移除,并为弱引用对象触发一个回调。
- 典型应用包括对创建开销较大的对象进行缓存:
import weakref, gc
class A:def __init__(self, value):self.value = valuedef __repr__(self):return str(self.value)a = A(10) # 创建一个引用
d = weakref.WeakValueDictionary()
d['primary'] = a
print(d['primary']) # 10del a # 移除引用print(gc.collect()) # 0print(d['primary']) # KeyError: 'primary'
- 用于操作列表的工具
array模块提供的array()对象,类似列表,但只储存一种数据类型>>> # 以两个字节为存储单元的无符号d二进制数值的数组(类型码为 'H')>>> from array import array>>> a = array([1, 2, 3, 4])Traceback (most recent call last):File "<stdin>", line 1, in <module>TypeError: array() argument 1 must be a unicode character, not list>>> a = array('H', [1, 2, 3, 4])>>> sum(a)10>>> a[0:2] # 切片array('H', [1, 2])>>>>>> aarray('H', [1, 2, 3, 4])collections 的 deque() 对象 队列,增删快,查找慢>>> from collections import deque>>> d = deque(['a', 'b', 'c', 'd'])>>> d.append('e')>>> ddeque(['a', 'b', 'c', 'd', 'e'])>>> print('出队, ', d.popleft())出队, a>>> ddeque(['b', 'c', 'd', 'e'])bisect(平分,二等分)模块操作排序列表的函数>>> import bisect as bi>>> scores = [(100, 'ruby'), (200, 'python'), (400, 'java'), (500, 'c')]>>> bi.insort(scores, (300, 'javascript')) # 按分数排序>>> scores[(100, 'ruby'), (200, 'python'), (300, 'javascript'), (400, 'java'), (500, 'c')]heapq 模块 基于列表来实现堆函数。 你可选择性的排序你要的列表。>>> from heapq import heapify, heappop, heappush>>> data = [2, 1, 4, 7, 5, 0, 9, 8, 3, 6]>>> heapify(data) # 按堆顺序重新排列列表>>> data[0, 1, 2, 3, 5, 4, 9, 8, 7, 6]>>> data[0, 1, 2, 3, 5, 4, 9, 8, 7, 6]>>> heappush(data, -1) # 添加-1>>> data[-1, 0, 2, 3, 1, 4, 9, 8, 7, 6, 5]>>> heappop(data) # 移除-1-1>>> data[0, 1, 2, 3, 5, 4, 9, 8, 7, 6]>>> [heappop(data) for i in range(3)] # 从堆中移除前三个数[0, 1, 2]>>> data[3, 5, 4, 6, 8, 7, 9]
decimal模块
• 财务应用和其他需要精确十进制表示的用途,
• 控制精度,
• 控制四舍五入以满足法律或监管要求,
• 跟踪有效小数位,或
• 用户期望结果与手工完成的计算相匹配的应用程序。
- 用decimal计算,和直接计算
>>> round(Decimal('0.70') * Decimal('1.05'), 2)Decimal('0.74')>>>>>> round(0.70 * 1.05, 2)0.73
- 对比float的浮点运算 和 比较
>>> Decimal('1.00') % Decimal('0.10')Decimal('0.00')>>>>>> 1.00 % 0.100.09999999999999995>>>>>> sum([Decimal('0.1')*10]) == Decimal('1.0')True>>> s = sum([0.1] * 10)>>> s0.9999999999999999>>> s == 1.0False
- decimal提供的精度
>>> getcontext().prec = 36>>> Decimal(1) / Decimal(7)Decimal('0.142857142857142857142857142857142857')
ps:学习笔记。请看:
python标准库(一)