random包
需要导入random包
import random
使用示例:
![](https://i-blog.csdnimg.cn/blog_migrate/452cac0cc280a4924403c08081e37c07.png)
![](https://i-blog.csdnimg.cn/blog_migrate/2391a21ab1dad1c49f0ebb4ac2a61142.png)
easydict
EasyDict允许以属性的形式访问字典值,且可以递归地访问。一种用于python字典属性的点表示法
from easydict import EasyDict
d = EasyDict()
d.foo=3
print(d.foo)
d = EasyDict(log=False)
d.debug = True
print(d.items())
class Flower(EasyDict):
power=1
f =Flower({“height”:12})
print(f.power)
print(f[“power”])
tqdm模块
简介
tqdm means “progress” in Arabic (taqadum, تقدّم)and an abbreviation for “I love you so much” in Spanish (te quiero demasiado).
Instantly make your loops show a smartprogress meter - just wrap any iterable withtqdm(iterable), and you’re done!
注意是:from tqdm import tqdm
![](https://i-blog.csdnimg.cn/blog_migrate/80613aa3ce9e265116e1fd8ef7d47aa0.png)
tqdm常用参数
with tqdm(total=100, desc='前缀', postfix='后缀', mininterval=0.3) as pbar:
for i in range(100):
time.sleep(0.1) # 休眠0.1s
pbar.update(1)
上述代码中total参数是进度条的总长度 ,desc参数是进度条的前缀,postfix是进度条的后缀,minterval代表进度条的最小更新时间间隔,time.sleep(0.1)模拟任务的执行;
pbar.update(1)代表代码运行到这里进度条就加1,也就是说,pbar.update(2)就代表加2。但是进度条的状态更新还要看参数niminterval,若不设置该参数,则就是运行到pbar.update处就马上更新。
tqdm加enumerate
最好是,tqdm要加在enumerate里面:
enumerate(tqdm(iter_object))
import os
from tqdm importtqdm
import time
if __name__ == '__main__':
x_list = [1, 2, 3, 4, 5]
# for i,x in enumerate(x_list):
# print(f"i: {i}, x: {x}")
# for i, x intqdm(enumerate(x_list)):
# print(f"i: {i}, x: {x}")
for i, x in tqdm(enumerate(x_list), total=len(x_list)):
# print(f"i: {i}, x:{x}")
time.sleep(1)
## 正确方式 ##
# for i, x inenumerate(tqdm(x_list)):
# # print(f"i: {i}, x: {x}")
# time.sleep(1)
多进程tqdm
with Pool(processes=4) as pool:
result = list(tqdm(pool.imap(func_s, np.linspace(0, 2 *math.pi, 1000)), total=1000))
print(result)
对pandas的DataFrame使用tqdm
csv_df = pd.DataFrame(np.random.random((10000, 3)))
for index, row in tqdm(csv_df.iterrows(), total=csv_df.shape[0]):
time.sleep(0.1)
with tqdm(total=len(list(csv_df.iterrows()))) as pbar:
for index, row in csv_df.iterrows():
pbar.update(1)
time.sleep(0.1)
glob模块
简介
查找包含给定字符串的文件unique
glob模块是最简单的模块之一,内容非常少。用它可以查找符合特定规则的文件路径名。跟使用windows下的文件搜索差不多。查找文件只用到三个匹配符:”*”, “?”, “[]”。”*”匹配0个或多个字符;”?”匹配单个字符;”[]”匹配指定范围内的字符,如:[0-9]匹配数字
glob.glob
返回所有匹配的文件路径列表。它只有一个参数pathname,定义了文件路径匹配规则,这里可以是绝对路径,也可以是相对路径。下面是使用glob.glob的例子:
import glob
#获取指定目录下的所有图片
print glob.glob(r"E:/Picture/*/*.jpg")
#获取上级目录的所有.py文件
print glob.glob(r'../*.py') #相对路径
glob.iglob
获取一个可编历对象,使用它可以逐个获取匹配的文件路径名。与glob.glob()的区别是:glob.glob同时获取所有的匹配路径,而glob.iglob一次只获取一个匹配路径。这有点类似于.NET中操作数据库用到的DataSet与DataReader。下面是一个简单的例子:
import glob
#父目录中的.py文件
f = glob.iglob(r'../*.py')
print f #<generator object iglob at 0x00B9FF80>
for py in f:
print(py)
pprint模块
pprint – 美观打印
作用:美观打印数据结构
pprint 包含一个“美观打印机”,用于生成数据结构的一个美观视图。格式化工具会生成数据结构的一些表示,不仅可以由解释器正确地解析,而且便于人类阅读。输出尽可能放在一行上,分解为多行时则需要缩进。
傅里叶变换包
scipy.fftpack和numpy.fft
声音的包
from lisa import audiosupport
audiosupport.beep()
itertools模块
Infinite Iterators(无穷迭代器)
![](https://i-blog.csdnimg.cn/blog_migrate/8001c17535cb427b2fe04e3c54a52dfb.png)
Iterators terminating on the shortest input sequence(迭代器终止于最短的输入序列)
![](https://i-blog.csdnimg.cn/blog_migrate/516d3e323208e2c8bf88993bcb8cdb78.png)
Combinatoric generators(组合学函数)
![](https://i-blog.csdnimg.cn/blog_migrate/5c0ffe9d2c19621a47cd909c373c87cf.png)
常用函数
itertools.groupby()方法
![](https://i-blog.csdnimg.cn/blog_migrate/04eea9996758b239a987ce919d7c5642.png)
difflib模块
difflib是python提供的比较序列(string list)差异的模块。
实现了三个类:
1>SequenceMatcher 任意类型序列的比较 (可以比较字符串)
2>Differ 对字符串进行比较
3>HtmlDiff 将比较结果输出为html格式.
符号 | 含义 |
'-' | 包含在第一个系列行中,但不包含第二个。 |
'+' | 包含在第二个系列行中,但不包含第一个。 |
' ' | 两个系列行一致 |
'?' | 存在增量差异 |
'^' | 存在差异字符 |
addict模块
下载
pip install addict
基本使用
from addict import Dict
configs = Dict()
configs.platform.status = "on"
configs.platform.web.task.name = "测试-1204"
configs.platform.web.periods.start = "2020-10-01"
configs.platform.web.periods.end = "2020-10-31"
click模块
Click 是 Flask 的团队 pallets 开发的优秀开源项目,它为命令行工具的开发封装了大量方法,使开发者只需要专注于功能实现
Click 是通过装饰器来把一个函数方法装饰成命令行接口的
retry模块
retry(exceptions=Exception, tries=-1,delay=0, max_delay=None, backoff=1, jitter=0, logger=logging_logger)
@retry((ValueError, TypeError), tries=8,delay=0.1, backoff=2, jitter=0.1, max_delay=1)
def make_trouble():
"""
Retry on ValueError or TypeError, sleep 0.1, 0.3, 0.7, 1, 1, ... secondsbetween attempts.
"""
print(1, time.time())
raise ValueError('a')
if __name__ == '__main__':
make_trouble()
collections模型
![](https://i-blog.csdnimg.cn/blog_migrate/d63a816e8af5a7efdd86a5dd9b704854.png)
counter
counter自有的三种方法:
![](https://i-blog.csdnimg.cn/blog_migrate/16670ba84b9288903af3f1f8f715011e.png)
counter的常用操作:
![](https://i-blog.csdnimg.cn/blog_migrate/4fe3b592639d7f0818e9795778dbc92a.png)
加减与交并:
![](https://i-blog.csdnimg.cn/blog_migrate/ff6da95c0b37c1e16df3252a06a8d3c0.png)
元加减操作:
![](https://i-blog.csdnimg.cn/blog_migrate/4690f32f85a84d3212226375c7ab5f13.png)
counter统计数量分布
统计数量分布
from collections import Counter
print(sorted(Counter(y).items()))
heapq
heapq.heappush(heap, item)
heapq.heapify(list)
heapq.heappop(heap)
heapq.heapreplace(heap.item)
heapq.heappushpop(list, item)
heapq.merge(…)
heapq.nlargest(n,heap)
heapq.nsmallest(n,heap)
比如:
cheap = heapq.nsmallest(3, portfolio, key=lambdas: s['price'])
expensive = heapq.nlargest(3,portfolio, key=lambda s: s['price'])
wmi
WMI (Windows Management Instrumentation) 模块可用于获取 Windows 内部信息,在使用Python获取Windows系统上的相关的信息可以使用WMI接口来获取。
WMI是一项核心的Windows管理技术,WMI作为一种规范和基础结构,通过它可以访问、配置、管理和监视几乎所有的Windows资源,比如用户可以在远程计算机器上启动一个进程;设定一个在特定日期和时间运行的进程;远程启动计算机;获得本地或远程计算机的已安装程序列表;查询本地或远程计算机的Windows事件日志等等。
该模块需要 win32com 的支持,环境安装如下,
pip install wmi
pip install pypiwin32
测试安装结果
>>> import win32con
>>> import wmi
导入模块没有报错,证明安装完成