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庫
html

Instavest上發表了一篇博文,文章分享了深受創業公司喜好的3款Python庫,該文章在Hacker News上引起了開發者的激烈探討。python

1.  Whitenoise(見上面)mysql

 

2. Phonenumbers(精簡版)linux

要識別出電話號碼不是件容易的事情,而正則表達式也不必定能處理好各類五花八門的有效電話格式。git

例如:程序員

  • 無效的:222-222-2222(這會經過正則測試)
  • 有效的:313-442-1231 外線. 901

可見依賴於單一的正則檢測不必定能獲得想要的答案,因此,要適當藉助工具—Phonenumbers。推薦緣由是它小巧,實用簡便,沒有地理代編碼,運營商,時區等metadata數據。它能識別多種格式,而後使用不一樣的格式/樣式進行有效匹配。github

3. Pdfkitweb

藉助Pdfkit能夠便捷地把HTML轉換成PDF文件。這有何用處呢?比方說你的應用有一個含有發票信息的頁面,你就能夠透過Pdfkit幫助生成一個PDF文件供用戶進行下載,其用法以下:正則表達式

 

[python]  view plain  copy
 
  1. import pdfkit    
  2.     
  3. pdfkit.from_file('test.html', 'out.pdf')    
  4.    
  5. # Generating PDFs from strings and web-pages is equally easy:    
  6.     
  7. pdfkit.from_string('Hello!', 'out.pdf')    
  8. pdfkit.from_url('http://google.com', 'out.pdf')    

4.Python-dateutilsql

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]

[創業公司都在使用的3款Python庫]

皮皮blog

 

 

讓人耳目一新的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="John@gmail.com")  # create

User.at(2).update(email="John@github.com")  # 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))"

Pocoo小組

pocoo出的庫,必屬精品。 http://www.pocoo.org/

它的庫很出名: flask, jinja2, pygments,sphinx

[讓人耳目一新的Python庫]

皮皮blog

 

 

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 這類知名的庫,月下載量也只有幾十萬。

 

[Github上Python開發者應該關心的Repo]

 

 

你可能沒聽過的11個Python庫

2) prettytable

你可能從未聽過該庫,由於它託管在GoogleCode。prettytable主要用於在終端或瀏覽器端構建很好的輸出。

[py]  view plain copy
 
 
  1. from prettytable import PrettyTable  
  2. table = PrettyTable(["animal", "ferocity"])  
  3. table.add_row(["wolverine", 100])  
  4. table.add_row(["grizzly", 87])  
  5. table.add_row(["Rabbit of Caerbannog", 110])  
  6. table.add_row(["cat", -1])  
  7. table.add_row(["platypus", 23])  
  8. table.add_row(["dolphin", 63])  
  9. table.add_row(["albatross", 44])  
  10. table.sort_key("ferocity")  
  11. table.reversesort = True  
  12. +----------------------+----------+  
  13. |        animal        | ferocity |  
  14. +----------------------+----------+  
  15. | Rabbit of Caerbannog |   110    |  
  16. |      wolverine       |   100    |  
  17. |       grizzly        |    87    |  
  18. |       dolphin        |    63    |  
  19. |      albatross       |    44    |  
  20. |       platypus       |    23    |  
  21. |         cat          |    -1    |  
  22. +----------------------+----------+  

3.snowballstemmer

好吧,我也是首次安裝該庫。這是一款很是瘦小的語言轉換庫,支持15種語言。

 

[py]  view plain copy
 
 
  1. from snowballstemmer import EnglishStemmer, SpanishStemmer  
  2. EnglishStemmer().stemWord("Gregory")  
  3. # Gregori  
  4. SpanishStemmer().stemWord("amarillo")  
  5. # amarill  

4.wget

你是否還記得,每一次都會由於某個目的而編寫網絡爬蟲工具,之後不再用了,由於wget就足夠你使用了。wget是Python版的網絡爬蟲庫,簡單好用。

 

[py]  view plain copy
 
 
  1. import wget  
  2. wget.download("http://www.cnn.com/")  
  3. # 100% [............................................................................] 280385 / 280385  
備註:linux和osx用戶這樣用:from sh import wget。可是,wget模塊還有一個更好的argument handline。

 

5.PyMC

scikit-learn彷佛是全部人的寵兒,但在我看來,PyMC更有魅力。PyMC主要用來作Bayesian分析。 

 

[py]  view plain copy
 
 
  1. from pymc.examples import disaster_model  
  2. from pymc import MCMC  
  3. M = MCMC(disaster_model)  
  4. M.sample(iter=10000, burn=1000, thin=10)  
  5. [-----------------100%-----------------] 10000 of 10000 complete in 1.4 sec  

 

7.fuzzywuzzy

 

 

Fuzzywuzzy是一個能夠對字符串進行模糊匹配的庫,你們有空能夠去 查看源碼。 

 

[py]  view plain copy
 
 
  1. from fuzzywuzzy import fuzz  
  2. fuzz.ratio("Hit me with your best shot", "Hit me with your pet shark")  
  3. # 85  
8.progressbar

 

 

 

 

progressbar是一個進度條庫,該庫提供了一個文本模式的progressbar。 

 

[py]  view plain copy
 
 
  1. from progressbar import ProgressBar  
  2. import time  
  3. pbar = ProgressBar(maxval=10)  
  4. for i in range(1, 11):  
  5.     pbar.update(i)  
  6.     time.sleep(1)  
  7. pbar.finish()  
  8. # 60% |########################################################                                      |  

9.colorama

colorama主要用來給文本添加各類顏色,而且很是簡單易用。

 


11.bashplotlib

 

bashplotlib是一個繪圖庫,它容許你使用stdin繪製柱狀圖和散點圖等。 

 

[py]  view plain copy
 
 
  1. $ pip install bashplotlib  
  2. $ scatter --file data/texas.txt --pch x  
 

[你可能沒聽過的11個Python庫]

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

相關文章
相關標籤/搜索