11. 标准库简介 —— 第二部分

第二部分涵盖了专业编程所需要的更高级的模块。这些模块很少用在小脚本中。

11.1. 格式化输出

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 stringsinstead of one big string with newlinesto separate the wrapped lines.

>>> 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. 模板

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.jpgimg_1076.jpg --> Ashley_1.jpgimg_1077.jpg --> Ashley_2.jpg

11.3. 使用二进制数据记录格式

struct 模块提供了 pack() 和 unpack() 函数,用于处理不定长度的二进制记录格式。下面的例子展示了在不使用 zipfile 模块的情况下,如何循环遍历一个 ZIP 文件的所有头信息。Pack 代码 "H" 和 "I" 分别代表两字节和四字节无符号整数。" 代表它们是标准尺寸的小尾型字节序:

import structwith open('myfile.zip', 'rb') as f:    data = f.read()start = 0for i in range(3):                      # show the first 3 file headers    start += 14    fields = struct.unpack(', data[start:start+16])    crc32, comp_size, uncomp_size, filenamesize, extra_size = fields    start += 16    filename = data[start:start+filenamesize]    start += filenamesize    extra = data[start:start+extra_size]print(filename, hex(crc32), comp_size, uncomp_size)    start += extra_size + comp_size     # skip to the next header

11.4. 多线程

import threading, zipfileclass 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('Finished background zip of:', self.infile)background = AsyncZip('mydata.txt', 'myarchive.zip')background.start()print('The main program continues to run in foreground.')background.join()    # Wait for the background task to finishprint('Main program waited until background was done.')

11.5. 日志记录

logging 模块提供功能齐全且灵活的日志记录系统。在最简单的情况下,日志消息被发送到文件或 sys.stderr

import logginglogging.debug('Debugging information')logging.info('Informational message')logging.warning('Warning:config file %s not found', 'server.conf')logging.error('Error occurred')logging.critical('Critical error -- shutting down')

11.6. 弱引用

>>> import weakref, gc>>> class A:...     def __init__(self, value):...         self.value = value...     def __repr__(self):...         return str(self.value)...>>> a = A(10)                   # create a reference>>> d = weakref.WeakValueDictionary()>>> d['primary'] = a            # does not create a reference>>> d['primary']                # fetch the object if it is still alive10>>> del a                       # remove the one reference>>> gc.collect()                # run garbage collection right away0>>> d['primary']                # entry was automatically removedTraceback (most recent call last):  File "", line 1, in     d['primary']                # entry was automatically removed  File "C:/python38/lib/weakref.py", line 46, in __getitem__    o = self.data[key]()KeyError: 'primary'

11.7. 用于操作列表的工具

在替代的列表实现以外,标准库也提供了其他工具,例如 bisect 模块具有用于操作排序列表的函数:

>>> import bisect>>> scores = [(100, 'perl'), (200, 'tcl'), (400, 'lua'), (500, 'python')]>>> bisect.insort(scores, (300, 'ruby'))>>> scores[(100, 'perl'), (200, 'tcl'), (300, 'ruby'), (400, 'lua'), (500, 'python')]

heapq 模块提供了基于常规列表来实现堆的函数。最小值的条目总是保持在位置零。这对于需要重复访问最小元素而不希望运行完整列表排序的应用来说非常有用:

>>> from heapq import heapify, heappop, heappush>>> data = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]>>> heapify(data)                      # rearrange the list into heap order>>> heappush(data, -5)                 # add a new entry>>> [heappop(data) for i in range(3)]  # fetch the three smallest entries[-5, 0, 1]

11.8. 十进制浮点运算


阅读笔记

本节简单描述了高阶码农可能会涉足的标准库,看代码一目了然。

python struct pack_Python(12)教程11.标准库简介——第二部分相关推荐

  1. 对象数组参数_【JavaScript 教程】标准库—Array 对象

    作者 | 阮一峰 1.构造函数 Array是 JavaScript 的原生对象,同时也是一个构造函数,可以用它生成新的数组. var arr = new Array(2);arr.length // ...

  2. python函数库_10. 标准库简介

    10.标准库简介¶ 10.1.操作系统接口¶ os 模块提供了许多与操作系统交互的函数: >>>import os >>>os.getcwd() # Return ...

  3. 后端返回number类型数据_【JavaScript 教程】标准库—Number 对象

    作者 | 阮一峰 1.概述 Number对象是数值对应的包装对象,可以作为构造函数使用,也可以作为工具函数使用. 作为构造函数时,它用于生成值为数值的对象. var n = new Number(1) ...

  4. Python标准库简介

    很系统的简介了Python标准库的使用方向,对形成知识框架很有帮助. 作者:Vamei 出处:http://www.cnblogs.com/vamei 欢迎转载,也请保留这段声明.谢谢! Python ...

  5. C++11标准库 - array 1

    C++11标准库 - array std::array是原生数组的封装,它存放于栈上且大小固定,性能也与之相同.在原生数组的基础上,它添加了范围检查,以及其它的STL的相应特性,比如复制.交换.迭代器 ...

  6. c语言标准库 菜鸟教程,C 标准库 – locale.h | 菜鸟教程

    C 标准库 - 简介 locale.h 头文件定义了特定地域的设置,比如日期格式和货币符号.接下来我们将介绍一些宏,以及一个重要的结构 struct lconv 和两个重要的函数. 库宏 下面列出了头 ...

  7. Python书籍推荐:《Python3标准库》

    最近双十一气氛弥漫在整个互联网,不买点东西总觉得缺了什么.在逛某东的时候无意中发现了这本刚出版没多久的书,一时心血来潮立即加入购物车,这不对啊,价格这么贵,而且优惠套路太多了.去当当一看,五折,99. ...

  8. python守护进程进程池_Python3标准库:multiprocessing像线程一样管理进程

    Python Python开发 Python语言 Python3标准库:multiprocessing像线程一样管理进程 1. multiprocessing像线程一样管理进程 multiproces ...

  9. 简明Python3教程 16.标准库

    简介 python标准库作为python标准安装的一部分,其自身包含数量庞大的实用模块, 因此熟悉python标准库非常重要,因为很多问题都能利用python标准库快速解决. 下面我们将研究标准库中的 ...

  10. python的input()函数与getpass标准库

    1. input()函数给我们提供了从键盘输入数据的途径,我们经常用这个函数来读入用户名等一些可以明文显示的数据.但是对于像密码这样的要密文显示的场景,这个函数就显得不安全了.因此python也给我们 ...

最新文章

  1. Linux系统介绍 文本查看、操作、统计命令(head/tail cat/tac less/more • wc sort uniq • cut paste)
  2. SQL INNER JOIN LEFT JOIN RIGHT JOIN 笛卡尔积
  3. 让我们来开发一种更类似人脑的神经网络吧(五)
  4. vc6.0制作窗体可嵌入IE内的OCX
  5. 他被女朋友拉黑后,写了个“舔狗”必备神器
  6. css flex排序居中
  7. Oracle occi 抓包,instantclient 32下载-instantclient-basic(轻量级数据库)32位 11.2.0.4.0 官方版 - 河东下载站...
  8. bug in MicrosoftAjax.debug.js
  9. 新手学vue还是react?
  10. Android-Universal-Image-Loader学习笔记(二)--LruDiscCache
  11. Linux 复制文件
  12. 巴菲特投资赚钱的赚钱宝典和赢家暗语
  13. 联网时显示已连接无法连接到服务器怎么办,路由器显示已连接不可上网怎么办?...
  14. 测试同学反馈,java 程序内存泄露,症状是RSS不断增加超过了jvm的xmx
  15. MIS和MES的区别
  16. RTK固定解什么意思
  17. 经验 | 如何编写优质嵌入式C代码
  18. Vue教程03-Vue脚手架开发环境
  19. 论文精读《LSS: Lift, Splat, Shoot: Encoding Images from Arbitrary Camera Rigs by Implicitly Unprojecting》
  20. A/B compartment:染色质区室简介

热门文章

  1. mybatis foreach标签的使用
  2. springboot整合mybatis-pluss、sharding-JDBC 水平分表demo
  3. Linux之用户/组管理以及任务调度学习总结
  4. js获得浏览器高度和宽度 参数
  5. Android内存优化12 内存泄漏常见情况3 注册泄漏
  6. 用 JavaScript 实现内存位翻转漏洞
  7. Pointer is missing a nullability type specifier (__nonnull or __nullable)
  8. mysqldump全量+增量备份
  9. flex学习笔记 数据验证
  10. linux系统工程师的前途在哪里