python模組 - 常用模組推薦
python常用模組
#取行數
import linecache
count = linecache.getlines('mv')[1]
print(count)
壓縮字元
當談起壓縮時我們通常想到檔案,比如ZIP結構。在Python中可以壓縮長字元,不涉及任何檔案檔案。import zlib
string = """ Lorem ipsum dolor sit amet, consectetur
adipiscing elit. Nunc ut elit id mi ultricies
adipiscing. Nulla facilisi. Praesent pulvinar,
sapien vel feugiat vestibulum, nulla dui pretium orci,
non ultricies elit lacus quis ante. Lorem ipsum dolor
sit amet, consectetur adipiscing elit. Aliquam
pretium ullamcorper urna quis iaculis. Etiam ac massa
sed turpis tempor luctus. Curabitur sed nibh eu elit
mollis congue. Praesent ipsum diam, consectetur vitae
ornare a, aliquam a nunc. In id magna pellentesque
tellus posuere adipiscing. Sed non mi metus, at lacinia
augue. Sed magna nisi, ornare in mollis in, mollis
sed nunc. Etiam at justo in leo congue mollis.
Nullam in neque eget metus hendrerit scelerisque
eu non enim. Ut malesuada lacus eu nulla bibendum
id euismod urna sodales. """
print "Original Size: {0}".format(len(string))
compressed = zlib.compress(string)
print "Compressed Size: {0}".format(len(compressed))
decompressed = zlib.decompress(compressed)
print "Decompressed Size: {0}".format(len(decompressed))
# output
# Original Size: 1022
# Compressed Size: 423
# Decompressed Size: 1022
註冊Shutdown函式
有個模組叫atexit,它可以讓你在指令碼執行完後立馬執行一些程式碼。假如你想在指令碼執行結束時測量一些基準資料,比如運行了多長時間:
import atexit
import time
import math
def microtime(get_as_float = False) :
if get_as_float:
return time.time()
else:
return '%f %d' % math.modf(time.time())
start_time = microtime(False)
atexit.register(start_time)
def shutdown():
global start_time
print "Execution took: {0} seconds".format(start_time)
atexit.register(shutdown)
# Execution took: 0.297000 1387135607 seconds
# Error in atexit._run_exitfuncs:
# Traceback (most recent call last):
# File "C:\Python27\lib\atexit.py", line 24, in _run_exitfuncs
# func(*targs, **kargs)
# TypeError: 'str' object is not callable
# Error in sys.exitfunc:
# Traceback (most recent call last):
# File "C:\Python27\lib\atexit.py", line 24, in _run_exitfuncs
# func(*targs, **kargs)
# TypeError: 'str' object is not callable
打眼看來很簡單。只需要將程式碼新增到指令碼的最底層,它將在指令碼結束前執行。但如果指令碼中有一個致命錯誤或者指令碼被使用者終止,它可能就不運行了。
當你使用atexit.register()時,你的程式碼都將執行,不論指令碼因為什麼原因停止執行(如這裡atexit.register(start_time)出錯,register接受的是函式物件而不是字串,出錯了,但是後面的atexit.register(shutdown)還是執行了,輸出為Execution took: 0.297000 1387135607 seconds)。
創業公司喜愛的3款Python庫
Instavest上發表了一篇博文,文章分享了深受創業公司喜愛的3款Python庫,該文章在Hacker News上引發了開發者的激烈探討。
1. Whitenoise(見上面)
2.Phonenumbers(精簡版)
要識別出電話號碼不是件容易的事情,而正則表示式也不一定能處理好各種五花八門的有效電話格式。
例如:
- 無效的:222-222-2222(這會通過正則測試)
- 有效的:313-442-1231 外線. 901
可見依賴於單一的正則檢測不一定能得到想要的答案,所以,要適當藉助工具—Phonenumbers。推薦原因是它小巧,實用簡便,沒有地理代編碼,運營商,時區等metadata資料。它能識別多種格式,然後使用不同的格式/樣式進行有效匹配。
3.Pdfkit
藉助Pdfkit可以便捷地把HTML轉換成PDF檔案。這有何用處呢?比方說你的應用有一個含有發票資訊的頁面,你就可以透過Pdfkit幫助生成一個PDF檔案供使用者進行下載,其用法如下:
- importpdfkit
- pdfkit.from_file('test.html','out.pdf')
- #GeneratingPDFsfromstringsandweb-pagesisequallyeasy:
- pdfkit.from_string('Hello!','out.pdf')
- pdfkit.from_url('http://google.com','out.pdf')
4.Python-dateutil
Numerous date utilities for calculating differences, etc. The most useful of these is a resilient date parser:
import dateutil.parser
>>> dateutil.parser.parse("May 4th, 2012")
datetime.datetime(2012, 5, 4, 0, 0)
>>> dateutil.parser.parse("5-4-2012")
datetime.datetime(2012, 5, 4, 0, 0)
>>> dateutil.parser.parse("5.4.2012")
datetime.datetime(2012, 5, 4, 0, 0)
>>> dateutil.parser.parse("4th May 2012")
datetime.datetime(2012, 5, 4, 0, 0) [
Three Useful Python Libraries for Startups]
讓人耳目一新的Python庫
purl
github:https://github.com/codeinthehole/purl
擁有簡潔介面的URL處理器:
>>> from purl import URL >>> from_str = URL('https://www.google.com/search?q=testing') >>> u.query_param('q') u'testing' >>> u.host() u'www.google.com'
path.py
github:https://github.com/jaraco/path.py
一個檔案系統處理庫,不過目前還在開發階段
from path import path
d = path('/home/guido/bin')
for f in d.files('*.py'):
f.chmod(0755)
Peewee
https://github.com/coleifer/peewee
小型ORM, 介面很漂亮:
# get tweets by editors ("<<" maps to IN)
Tweet.select().where(Tweet.user << editors) # how many active users are there? User.select().where(User.active == True).count()
類似的我的 CURD.py (https://github.com/hit9/CURD.py) :)
User.create(name="John", email="[email protected]") # create User.at(2).update(email="[email protected]") # update John = User.where(name="John").select().fetchone() # read # who wrote posts? for post, user in (Post & User).select().fetchall(): print "Author: %s, PostName: %s" % (user.name, post.name)
Pony ORM
https://github.com/ponyorm/pony
一個十分獨特的ORM,介面簡單幹淨,最大的特點是支援使用generator的語法來進行查詢,可以使查詢語句變得簡潔,靈活,而且漂亮。
例如可以使用如下的語句來進行一個查詢:
select(p for p in Product if p.name.startswith('A') and p.cost <= 1000)
同時,Pony ORM還提供了一個ER圖編輯工具來進行資料庫原型設計。
schema
https://github.com/halst/schema
同樣是docopt的作者編寫的,一個數據格式檢查庫,非常新穎:
>>> from schema import Schema >>> Schema(int).validate(123) 123 >>> Schema(int).validate('123') Traceback (most recent call last): ... SchemaError: '123' should be instance of <type 'int'> Traceback (most recent call last): ... SchemaError: '123' should be instance of <type 'int'>
fn.py
https://github.com/kachayev/fn.py
增強Python的函數語言程式設計:
from fn import _
print (_ + 2) # "(x1) => (x1 + 2)" print (_ + _ * _) # "(x1, x2, x3) => (x1 + (x2 * x3))"
Github上Python開發者應該關心的Repo
carbaugh/lice
lice: Generate license files for your projects
一個用來為你的專案生成許可證的工具。這下可方便了,不用手工的去修改了!
coleifer/peewee
peewee: a small, expressive orm – supports postgresql, Mysql and sqlite
你在用SQLAlchemy ? 我強烈推薦你看下peewee
來看一個sample:
User.select().where(User.active == True).order_by(User.username)
一個單檔案的Python ORM.相當輕巧,支援三個資料庫。而且,它最討人喜歡的是它的輕量級的語法。
hhatto/autopep8
autopep8: A tool that automatically formats Python code to conform to the PEP 8 style guide.
每個Python程式設計師都應該checkout的repo.自動的把你的Python程式碼轉成符合PEP8風格的程式碼.
使用-i引數來直接修改你的 Python檔案:
autopep8 -i mycode.py
kachayev/fn.py
fn.py: Functional programming in Python: implementation of missing features to enjoy FP
這是個很有趣的專案,來彌補Python在函數語言程式設計方面沒有的一些特性。來看個sample:
from fn import _
assert list(map(_ * 2, range(5))) == [0,2,4,6,8]
faif/python-patterns
python-patterns: A collection of design patterns implemented (by other people) in python
這個repo收集了很多設計模式的python寫法
gutworth/six/
six: Six is a Python 2 and 3 compatibility library
Six沒有託管在Github上,而是託管在了Bitbucket上,不過這些都不是重點,重點是它的作用。
眾所周知 Python 2 和 Python 3 版本的分裂給 Python 開發者們帶來了很大的煩惱,為了使程式碼同時相容兩個版本,往往要增加大量的程式碼。 於是 Six 出現了。正如它的介紹所說,它是一個專門用來相容 Python 2 和 Python 3 的庫。它解決了諸如 urllib 的部分方法不相容, str 和 bytes 型別不相容等“知名”問題。
它的效果怎麼樣?pypi上單日十萬以上,單月幾百萬的下載量足以說明了。要知道諸如 Flask 和 Django 這類知名的庫,月下載量也只有幾十萬。
你可能沒聽過的11個Python庫
你可能從未聽過該庫,因為它託管在GoogleCode。prettytable主要用於在終端或瀏覽器端構建很好的輸出。
- fromprettytableimportPrettyTable
- table=PrettyTable(["animal","ferocity"])
- table.add_row(["wolverine",100])
- table.add_row(["grizzly",87])
- table.add_row(["RabbitofCaerbannog",110])
- table.add_row(["cat",-1])
- table.add_row(["platypus",23])
- table.add_row(["dolphin",63])
- table.add_row(["albatross",44])
- table.sort_key("ferocity")
- table.reversesort=True
- +----------------------+----------+
- |animal|ferocity|
- +----------------------+----------+
- |RabbitofCaerbannog|110|
- |wolverine|100|
- |grizzly|87|
- |dolphin|63|
- |albatross|44|
- |platypus|23|
- |cat|-1|
- +----------------------+----------+
好吧,我也是首次安裝該庫。這是一款非常瘦小的語言轉換庫,支援15種語言。
- fromsnowballstemmerimportEnglishStemmer,SpanishStemmer
- EnglishStemmer().stemWord("Gregory")
- #Gregori
- SpanishStemmer().stemWord("amarillo")
- #amarill
4.wget
你是否還記得,每一次都會因為某個目的而編寫網路爬蟲工具,以後再也不用了,因為wget就足夠你使用了。wget是Python版的網路爬蟲庫,簡單好用。
- importwget
- wget.download("http://www.cnn.com/")
- #100%[............................................................................]280385/280385
5.PyMC
scikit-learn似乎是所有人的寵兒,但在我看來,PyMC更有魅力。PyMC主要用來做Bayesian分析。
- frompymc.examplesimportdisaster_model
- frompymcimportMCMC
- M=MCMC(disaster_model)
- M.sample(iter=10000,burn=1000,thin=10)
- [-----------------100%-----------------]10000of10000completein1.4sec
Fuzzywuzzy是一個可以對字串進行模糊匹配的庫,大家有空可以去檢視原始碼。
- fromfuzzywuzzyimportfuzz
- fuzz.ratio("Hitmewithyourbestshot","Hitmewithyourpetshark")
- #85
progressbar是一個進度條庫,該庫提供了一個文字模式的progressbar。
- fromprogressbarimportProgressBar
- importtime
- pbar=ProgressBar(maxval=10)
- foriinrange(1,11):
- pbar.update(i)
- time.sleep(1)
- pbar.finish()
- #60%|########################################################|
9.colorama
colorama主要用來給文字新增各種顏色,並且非常簡單易用。

11. bashplotlib
bashplotlib是一個繪相簿,它允許你使用stdin繪製柱狀圖和散點圖等。
- $pipinstallbashplotlib
- $scatter--filedata/texas.txt--pchx

[英文原文:11 Python Libraries You Might Not Know]

