Python開發者應該知道的7個開發庫
在我多年的 Python 編程經曆以及在 Github 上的探索漫遊過程中,我發掘到一些很不錯的 Python 開發包,這些包大大簡化了開發過程,而本文就是為了向大家推薦這些開發包。
請注意我特別排除了像SQLAlchemy和Flask這樣的庫,因為其實在太優秀了,無需多提。
下麵開始:
1. PyQuery (with lxml)
安裝方法 pip install pyquery
Python 解析 HTML 時最經常被推薦的是Beautiful Soup ,而且它的確也表現很好。提供良好的 Python 風格的 API,而且很容易在網上找到相關的資料文檔,但是當你需要在短時間內解析大量文檔時便會碰到性能的問題,簡單,但是真的非常慢。
下圖是 08 年的一份性能比較圖:
這個圖裏我們發現 lxml 的性能是如此之好,不過文檔就很少,而且使用上相當的笨拙!那麼是選擇一個使用簡單但是速度奇慢的庫呢,還是選擇一個速度飛快但是用起來巨複雜的庫呢?
誰說二者一定要選其一呢,我們要的是用起來方便,速度也一樣飛快的 XML/HTML 解析庫!
而 PyQuery 就可以同時滿足你的易用性和解析速度方麵的苛刻要求。
看看下麵這幾行代碼:
- from pyquery import PyQuery
- page = PyQuery(some_html)
- last_red_anchor = page('#container > a.red:last')
很簡單吧,很像是 jQuery,但它卻是 Python。
不過也有一些不足,在使用迭代時需要對文本進行重新封裝:
- for paragraph in page('#container > p'):
- paragraph = PyQuery(paragraph)
- text = paragraph.text()
2. dateutil
安裝方法:pip install dateutil
處理日期很痛苦,多虧有了 dateutil
- from dateutil.parser import parse
- >>> parse('Mon, 11 Jul 2011 10:01:56 +0200 (CEST)')
- datetime.datetime(2011, 7, 11, 10, 1, 56, tzinfo=tzlocal())
- # fuzzy ignores unknown tokens
- >>> s = """Today is 25 of September of 2003, exactly
- ... at 10:49:41 with timezone -03:00."""
- >>> parse(s, fuzzy=True)
- datetime.datetime(2003, 9, 25, 10, 49, 41,
- tzinfo=tzoffset(None, -10800))
3. fuzzywuzzy
安裝方法:pip install fuzzywuzzy
fuzzywuzzy 可以讓你對兩個字符串進行模煳比較,當你需要處理一些人類產生的數據時,這非常有用。下麵代碼使用Levenshtein 距離比較方法來匹配用戶輸入數組和可能的選擇。
- from Levenshtein import distance
- countries = ['Canada', 'Antarctica', 'Togo', ...]
- def choose_least_distant(element, choices):
- 'Return the one element of choices that is most similar to element'
- return min(choices, key=lambda s: distance(element, s))
- user_input = 'canaderp'
- choose_least_distant(user_input, countries)
- >>> 'Canada'
這已經不錯了,但還可以做的更好:
- from fuzzywuzzy import process
- process.extractOne("canaderp", countries)
- >>> ("Canada", 97)
4. watchdog
安裝方法:pip install watchdog
watchdog 是一個用來監控文件係統事件的 Python API和shell實用工具。
5. sh
安裝方法:pip install sh
sh 可讓你調用任意程序,就好象是一個函數一般:
- from sh import git, ls, wc
- # checkout master branch
- git(checkout="master")
- # print(the contents of this directory
- print(ls("-l"))
- # get the longest line of this file
- longest_line = wc(__file__, "-L")
6. pattern
安裝方法:pip install pattern
Pattern 是 Python 的一個 Web 數據挖掘模塊。可用於數據挖掘、自然語言處理、機器學習和網絡分析。
7. path.py
安裝方法:pip install path.py
當我開始學習 Python 時,os.path 是我最不喜歡的 stdlib 的一部分。盡管在一個目錄下創建一組文件很簡單。
- import os
- some_dir = '/some_dir'
- files = []
- for f in os.listdir(some_dir):
- files.append(os.path.joinpath(some_dir, f))
但listdir在os而不是os.path中。
而有了path.py ,處理文件路徑變得簡單:
- from path import path
- some_dir = path('/some_dir')
- files = some_dir.files()
其他的用法:
- >>> path('/').owner
- 'root'
- >>> path('a/b/c').splitall()
- [path(''), 'a', 'b', 'c']
- # overriding __div__
- >>> path('a') / 'b' / 'c'
- path('a/b/c')
- >>> path('ab/c').relpathto('ab/d/f')
- path('../d/f')
是不是要好很多?
最後更新:2017-04-03 22:30:57