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文件供用户进行下载,其用法如下:

 

[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-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]

[创业公司都在使用的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 plaincopy在CODE上查看代码片派生到我的代码片
 
 
  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 plaincopy在CODE上查看代码片派生到我的代码片
 
 
  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 plaincopy在CODE上查看代码片派生到我的代码片
 
 
  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 plaincopy在CODE上查看代码片派生到我的代码片
 
 
  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 plaincopy在CODE上查看代码片派生到我的代码片
 
 
  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 plaincopy在CODE上查看代码片派生到我的代码片
 
 
  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 plaincopy在CODE上查看代码片派生到我的代码片
 
 
  1. $ pip install bashplotlib  
  2. $ scatter --file data/texas.txt --pch x  

[你可能没听过的11个Python库]

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

 

 

哪些 Python 库让你相见恨晚?

Watchdog:Watchdog — watchdog 0.8.0 documentation监视文件系统改动。

Path:API — path.py 5.2 documentation简化文件系统相关操作。

 

 
posted @ 2017-12-08 17:48  『心向阳﹡无所惧』  阅读(872)  评论(0编辑  收藏  举报