分享一些提升編程效率的輪子
這里從字母 A 到 Z 的順序進(jìn)行,有些屬于標(biāo)準(zhǔn)庫,可以直接導(dǎo)入使用,有些屬于第三方庫,需要 pip install 后使用。
1、all or any
為什么 Python 如此流行,一個(gè)重要的原因就是 Python 的代碼是人類可讀的,生動(dòng)形象的,比如 all or any 這個(gè)用法:
- 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")
上面的代碼,我相信完全不用注釋,你都能看懂,后續(xù)編程時(shí)不要忘了用。
2、bashplotlib[1]
正如的它的名字一樣,可以在 bash 控制臺(tái)下面畫圖,舉個(gè)🌰:現(xiàn)在我們有一個(gè)文本文件,里面一列數(shù)字,如何快速進(jìn)行統(tǒng)計(jì)呢,直接使用 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]:
也可以直接使用命令行:
- (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
還可以使用 scatter 繪制 x、y 坐標(biāo),詳情請(qǐng)?jiān)L問 bashplotlib 文檔[2]
3、collections
Python 的基本數(shù)據(jù)類型很好用,但有時(shí)無法按照我們希望的那樣快速初始化。比如說我希望有一個(gè)字典,它的值是一個(gè)列表,定義好之后想直接插入數(shù)據(jù),怎么辦?
通常會(huì)這樣:
- my_dict = {}
- if 'key' in my_dict:
- my_dict['key'].append('something')
- else:
- my_dict['key'] = ['something']
有了 collections 可以簡(jiǎn)化成這樣:
- from collections import defaultdict
- my_dict = defaultdict(list)
- my_dict['key'].append('something')
還有很多實(shí)用的類,比如:
詳細(xì)教程訪問 Python 官方文檔[3]。
4、dir
這是非常好用的內(nèi)省函數(shù)。如果你想看一個(gè) Python 類的內(nèi)部屬性,可別忘了 dir 函數(shù),比如說我想知道字符串都有哪些內(nèi)置的函數(shù),可以這樣:
- >>> 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']
5、emoji
如果想用 Python 在字符界面下打印出一個(gè)表情包,別忘了這個(gè):
- pip install emoji
6、from __future__ import
想使用未來的功能,可以的,舉個(gè)例子,你現(xiàn)在用的是 Python2,但是想用 Python3 的 print 函數(shù),可以!
- from __future__ import print_function
- print("Hello World!")
7、geopy
假如要處理地理位置信息,可以使用這個(gè),這是 google 的 api 接口,需要先申請(qǐng) app key。
- pip install geopy
- from geopy import GoogleV3
- place = "suzhou"
- location = GoogleV3().geocode(place)
- print(location.address)
- print(location.location)
8、howdoi
你在終端編程,此時(shí)想查看下如何使用 git 的 undo commits,不想離開終端,可以直接在終端里面查詢 StackOverflow:
- $ pip install howdoi
- $ howdoi undo commits in git
howdoi 會(huì)爬取 StackOverflow 置頂?shù)拇鸢福紶栆苍S不是最好的,但這已經(jīng)足以讓你保持專注了,記得用英語關(guān)鍵字去檢索。
9、inspect
Python 的 inspect 模塊非常適合了解代碼背后發(fā)生的事情。你甚至可以 inspect 自己檢查自己!
下面的代碼示例使用 inspect.getsource()打印自己的源代碼。它還使用 inspect.getmodule()打印在其中定義了該模塊的模塊。代碼的最后一行打印出自己的行號(hào)。
10、map
簡(jiǎn)單來說,map 函數(shù)的任務(wù)就是分發(fā)任務(wù)。
- x = [1, 2, 3]
- y = map(lambda x : x + 1 , x)
- # prints out [2,3,4]
- print(list(y))
11、newspaper3k
如果你需要獲取新聞、文章、文本的元數(shù)據(jù)(metadata)做自然語言訓(xùn)練,用這個(gè)就對(duì)了,可以大大提升你爬取網(wǎng)頁的效率。
- $ pip install newspaper3k
- >>> 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])
- 香港行政長(zhǎng)官梁振英在各方壓力下就其大宅的違章建
- 筑(僭建)問題到立法會(huì)接受質(zhì)詢,并向香港民眾道歉。
- 梁振英在星期二(12月10日)的答問大會(huì)開始之際
- 在其演說中道歉,但強(qiáng)調(diào)他在違章建筑問題上沒有隱瞞的
- 意圖和動(dòng)機(jī)。 一些親北京陣營(yíng)議員歡迎梁振英道歉,
- 且認(rèn)為應(yīng)能獲得香港民眾接受,但這些議員也質(zhì)問梁振英有
- >>> print(a.title)
- 港特首梁振英就住宅違建事件道歉
更多用法參考newspaper3k 文檔[4]。
12、pprint
全名叫 pretty print,意思就是漂亮的打印。比如說,對(duì)于一個(gè)復(fù)雜的字典,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'}}
而 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]:
是不是清爽了許多?
13、queue
queue 模塊是標(biāo)準(zhǔn)庫實(shí)現(xiàn)的一個(gè)同步的隊(duì)列類,實(shí)現(xiàn)了多生產(chǎn)者、多消費(fèi)者隊(duì)列。這特別適用于多線程間安全的交互消息。內(nèi)部有三個(gè)非常常用的隊(duì)列:Queue、LifoQueue、PriorityQueue。這些類在編程中有多重要就不多說了,做一做 leetCode 你就知道了。這里[5]有一些如何使用的例子。
14、sh
Python 是一種很棒的腳本語言,有時(shí)使用 os 和 subprocess 可能會(huì)讓人有些頭疼。sh 庫提供了一種巧妙的選擇,可以像調(diào)用普通程序一樣調(diào)用任何程序,這對(duì)從 Python 內(nèi)部進(jìn)行自動(dòng)化任務(wù)很有用。
- pip install sh
- import sh
- sh.pwd()
- sh.mkdir('new_folder')
- sh.touch('new_file.txt')
- sh.whoami()
- sh.echo('This is great!')
15、uuid
UUID 的全稱:Universally Unique Identifier,即通用唯一識(shí)別碼,通常作為數(shù)據(jù)庫的一個(gè)主鍵。
- In [26]: import uuid
- ...: user_id = uuid.uuid4()
- ...: print(user_id)
- 12d0957b-18e5-4a4a-b5ee-d38e5f2789ce
上述代碼會(huì)隨機(jī)產(chǎn)生 128 位的二進(jìn)制位,基本上不可能出現(xiàn)重復(fù),完全可以放心使用,即使重復(fù),再生成一個(gè)就是了。
16、venv
Python 3 自帶的創(chuàng)建虛擬環(huán)境的模塊,不需要再單獨(dú)安裝 virtualenv。
- python -m venv my-project
- source my-project/bin/activate
- pip install all-the-modules
17、YAML
YAML 的全稱是"YAML Ain't Markup Language",意思就是 YAML 不是標(biāo)記語言。它是一種數(shù)據(jù)格式語言,并且是JSON的超集。
與 JSON 不同,它可以存儲(chǔ)更復(fù)雜的對(duì)象并引用其自己的元素,還可以編寫注釋,使其特別適合編寫配置文件。
PyYAML 模塊使您可以將 YAML 與 Python 一起使用。
安裝方式:
- pip install pyyaml
比如說,我們有一段 yaml 格式的文本,可以快速轉(zhuǎn)換為 Python 對(duì)象:
- 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]:
最后的話
以上就是 17 個(gè) Python 非常實(shí)用的模塊或庫,可以大大提升你后續(xù)編程的效率。當(dāng)然 Python 的類庫眾多,你也會(huì)有一些自己壓箱底的工具庫,請(qǐng)?jiān)谙旅媪粞裕窒砟阕约合矚g的 Python 庫或者你需要的工具庫,一起討論,一起學(xué)習(xí)。