这里从字母 A 到 Z 的顺序进行,有些属于标准库,可以直接导入使用,有些属于第三方库,需要 pip install 后使用。
为什么 Python 如此流行,一个重要的原因就是 Python 的代码是人类可读的,生动形象的,比如 all or any 这个用法:
复制
x = [True, True, False] if any(x): print("At least one True") if all(x): print("Not one False") if any(x) and not all(x): print("At least one True and one False")
1.
2.
3.
4.
5.
6.
7.
上面的代码,我相信完全不用注释,你都能看懂,后续编程时不要忘了用。
正如的它的名字一样,可以在 bash 控制台下面画图,举个🌰:现在我们有一个文本文件,里面一列数字,如何快速进行统计呢,直接使用 plot_hist
复制
In [17]: !head -n 5 data/exp.txt 1.12578195876 0.16026238021 0.0392117875843 0.968428864579 0.334430039433 In [18]: from bashplotlib.histogram import plot_hist ...: In [19]: plot_hist(f="data/exp.txt",showSummary=True) 451| o 427| o 403| o 380| o 356| o 332| o 309| o 285| o 261| oo 238| oo 214| oo 190| oo 166| oo 143| oo 119| ooo 95| ooo 72| oooo 48| oooo 24| ooooo 1| ooooooooooo ----------- ----------------------------------- | Summary | ----------------------------------- | observations: 1000 | | min value: 0.001718 | | mean : 0.988786 | | max value: 6.552654 | ----------------------------------- In [20]:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
也可以直接使用命令行:
复制
(py38env) ➜ examples hist --file data/exp.txt 451| o 427| o 403| o 380| o 356| o 332| o 309| o 285| o 261| oo 238| oo 214| oo 190| oo 166| oo 143| oo 119| ooo 95| ooo 72| oooo 48| oooo 24| ooooo 1| ooooooooooo ----------- ----------------------------------- | Summary | ----------------------------------- | observations: 1000 | | min value: 0.001718 | | mean : 0.988786 | | max value: 6.552654 | ----------------------------------- (py38env) ➜ examples
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
还可以使用 scatter 绘制 x、y 坐标,详情请访问 bashplotlib 文档[2]
Python 的基本数据类型很好用,但有时无法按照我们希望的那样快速初始化。比如说我希望有一个字典,它的值是一个列表,定义好之后想直接插入数据,怎么办?
通常会这样:
复制
my_dict = {} if 'key' in my_dict: my_dict['key'].append('something') else: my_dict['key'] = ['something']
1.
2.
3.
4.
5.
6.
有了 collections 可以简化成这样:
复制
from collections import defaultdict my_dict = defaultdict(list) my_dict['key'].append('something')
1.
2.
3.
还有很多实用的类,比如:
详细教程访问 Python 官方文档[3]。
这是非常好用的内省函数。如果你想看一个 Python 类的内部属性,可别忘了 dir 函数,比如说我想知道字符串都有哪些内置的函数,可以这样:
复制
>>> dir("hello") ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
1.
2.
如果想用 Python 在字符界面下打印出一个表情包,别忘了这个:
复制
pip install emoji
1.
想使用未来的功能,可以的,举个例子,你现在用的是 Python2,但是想用 Python3 的 print 函数,可以!
复制
from __future__ import print_function print("Hello World!")
1.
2.
假如要处理地理位置信息,可以使用这个,这是 google 的 api 接口,需要先申请 app key。
复制
pip install geopy
1.
复制
from geopy import GoogleV3 place = "suzhou" location = GoogleV3().geocode(place) print(location.address) print(location.location)
1.
2.
3.
4.
5.
你在终端编程,此时想查看下如何使用 git 的 undo commits,不想离开终端,可以直接在终端里面查询 StackOverflow:
复制
$ pip install howdoi $ howdoi undo commits in git
1.
2.
howdoi 会爬取 StackOverflow 置顶的答案,偶尔也许不是最好的,但这已经足以让你保持专注了,记得用英语关键字去检索。
Python 的 inspect 模块非常适合了解代码背后发生的事情。你甚至可以 inspect 自己检查自己!
下面的代码示例使用 inspect.getsource()打印自己的源代码。它还使用 inspect.getmodule()打印在其中定义了该模块的模块。代码的最后一行打印出自己的行号。
简单来说,map 函数的任务就是分发任务。
复制
x = [1, 2, 3] y = map(lambda x : x + 1 , x) # prints out [2,3,4] print(list(y))
1.
2.
3.
4.
如果你需要获取新闻、文章、文本的元数据(metadata)做自然语言训练,用这个就对了,可以大大提升你爬取网页的效率。
复制
$ pip install newspaper3k
1.
复制
>>> from newspaper import Article >>> url = 'http://www.bbc.co.uk/zhongwen/simp/chinese_news/2012/12/121210_hongkong_politics.shtml' >>> a = Article(url, language='zh') # Chinese >>> a.download() >>> a.parse() >>> print(a.text[:150]) 香港行政长官梁振英在各方压力下就其大宅的违章建 筑(僭建)问题到立法会接受质询,并向香港民众道歉。 梁振英在星期二(12月10日)的答问大会开始之际 在其演说中道歉,但强调他在违章建筑问题上没有隐瞒的 意图和动机。 一些亲北京阵营议员欢迎梁振英道歉, 且认为应能获得香港民众接受,但这些议员也质问梁振英有 >>> print(a.title) 港特首梁振英就住宅违建事件道歉
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
更多用法参考newspaper3k 文档[4]。
全名叫 pretty print,意思就是漂亮的打印。比如说,对于一个复杂的字典,print 的效果是这样的一坨:
复制
In [16]: print(users) {'results': [{'gender': 'male', 'name': {'title': 'Mr', 'first': 'Fred', 'last': 'Cooper'}, 'location': {'street': {'number': 681, 'name': 'Victoria Street'}, 'city': 'Salisbury', 'state': 'Greater Manchester', 'country': 'United Kingdom', 'postcode': 'P1I 3XR', 'coordinates': {'latitude': '5.9123', 'longitude': '-22.2206'}, 'timezone': {'offset': '-2:00', 'description': 'Mid-Atlantic'}}, 'email': 'fred.cooper@example.com', 'login': {'uuid': '5261fb69-bc91-46ed-9e66-a4f6f51ff2ff', 'username': 'greenkoala692', 'password': 'teaser', 'salt': 'SVMfx7Z1', 'md5': 'e1d344cd5998cce8affbbdbeec358052', 'sha1': '083f8b9fb7e3271293af8d058fdf919fe690fb1a', 'sha256': '112e2d6838871ae2ca8aefb90c33f4850a537ee4d0d36c6f66bbcb5ed17b5da7'}, 'dob': {'date': '1959-12-04T14:20:29.781Z', 'age': 62}, 'registered': {'date': '2019-09-06T13:18:11.009Z', 'age': 2}, 'phone': '016977 6452', 'cell': '0794-684-745', 'id': {'name': 'NINO', 'value': 'NC 88 63 68 Q'}, 'picture': {'large': 'https://randomuser.me/api/portraits/men/40.jpg', 'medium': 'https://randomuser.me/api/portraits/med/men/40.jpg', 'thumbnail': 'https://randomuser.me/api/portraits/thumb/men/40.jpg'}, 'nat': 'GB'}], 'info': {'seed': '48254d6ef48036b0', 'results': 1, 'page': 1, 'version': '1.3'}}
1.
2.
而 pprint 的效果是有层次感的:
复制
In [19]: from pprint import pprint In [20]: pprint(users) {'info': {'page': 1, 'results': 1, 'seed': '48254d6ef48036b0', 'version': '1.3'}, 'results': [{'cell': '0794-684-745', 'dob': {'age': 62, 'date': '1959-12-04T14:20:29.781Z'}, 'email': 'fred.cooper@example.com', 'gender': 'male', 'id': {'name': 'NINO', 'value': 'NC 88 63 68 Q'}, 'location': {'city': 'Salisbury', 'coordinates': {'latitude': '5.9123', 'longitude': '-22.2206'}, 'country': 'United Kingdom', 'postcode': 'P1I 3XR', 'state': 'Greater Manchester', 'street': {'name': 'Victoria Street', 'number': 681}, 'timezone': {'description': 'Mid-Atlantic', 'offset': '-2:00'}}, 'login': {'md5': 'e1d344cd5998cce8affbbdbeec358052', 'password': 'teaser', 'salt': 'SVMfx7Z1', 'sha1': '083f8b9fb7e3271293af8d058fdf919fe690fb1a', 'sha256': '112e2d6838871ae2ca8aefb90c33f4850a537ee4d0d36c6f66bbcb5ed17b5da7', 'username': 'greenkoala692', 'uuid': '5261fb69-bc91-46ed-9e66-a4f6f51ff2ff'}, 'name': {'first': 'Fred', 'last': 'Cooper', 'title': 'Mr'}, 'nat': 'GB', 'phone': '016977 6452', 'picture': {'large': 'https://randomuser.me/api/portraits/men/40.jpg', 'medium': 'https://randomuser.me/api/portraits/med/men/40.jpg', 'thumbnail': 'https://randomuser.me/api/portraits/thumb/men/40.jpg'}, 'registered': {'age': 2, 'date': '2019-09-06T13:18:11.009Z'}}]} In [21]:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
是不是清爽了许多?
queue 模块是标准库实现的一个同步的队列类,实现了多生产者、多消费者队列。这特别适用于多线程间安全的交互消息。内部有三个非常常用的队列:Queue、LifoQueue、PriorityQueue。这些类在编程中有多重要就不多说了,做一做 leetCode 你就知道了。这里[5]有一些如何使用的例子。
Python 是一种很棒的脚本语言,有时使用 os 和 subprocess 可能会让人有些头疼。sh 库提供了一种巧妙的选择,可以像调用普通程序一样调用任何程序,这对从 Python 内部进行自动化任务很有用。
复制
pip install sh
1.
复制
import sh sh.pwd() sh.mkdir('new_folder') sh.touch('new_file.txt') sh.whoami() sh.echo('This is great!')
1.
2.
3.
4.
5.
6.
UUID 的全称:Universally Unique Identifier,即通用唯一识别码,通常作为数据库的一个主键。
复制
In [26]: import uuid ...: user_id = uuid.uuid4() ...: print(user_id) 12d0957b-18e5-4a4a-b5ee-d38e5f2789ce
1.
2.
3.
4.
上述代码会随机产生 128 位的二进制位,基本上不可能出现重复,完全可以放心使用,即使重复,再生成一个就是了。
Python 3 自带的创建虚拟环境的模块,不需要再单独安装 virtualenv。
复制
python -m venv my-project source my-project/bin/activate pip install all-the-modules
1.
2.
3.
YAML 的全称是"YAML Ain't Markup Language",意思就是 YAML 不是标记语言。它是一种数据格式语言,并且是JSON的超集。
与 JSON 不同,它可以存储更复杂的对象并引用其自己的元素,还可以编写注释,使其特别适合编写配置文件。
PyYAML 模块使您可以将 YAML 与 Python 一起使用。
安装方式:
复制
pip install pyyaml
1.
比如说,我们有一段 yaml 格式的文本,可以快速转换为 Python 对象:
复制
In [23]: import yaml In [24]: document = """ ...: a: 1 ...: b: ...: c: 3 ...: d: 4 ...: """ In [25]: yaml.load(document,Loader=yaml.FullLoader) Out[25]: {'a': 1, 'b': {'c': 3, 'd': 4}} In [26]:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
以上就是 17 个 Python 非常实用的模块或库,可以大大提升你后续编程的效率。当然 Python 的类库众多,你也会有一些自己压箱底的工具库,请在下面留言,分享你自己喜欢的 Python 库或者你需要的工具库,一起讨论,一起学习。