python模块 - 常用模块推荐
http://blog.csdn.net/pipisorry/article/details/47185795
python常用模块
压缩字符
当谈起压缩时我们通常想到文件,比如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文件供用户进行下载,其用法如下:
import pdfkit pdfkit.from_file('test.html', 'out.pdf') # Generating PDFs from strings and web-pages is equally easy: 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="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))"
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 这类知名的库,月下载量也只有几十万。
])
Fuzzywuzzy是一个可以对字符串进行模糊匹配的库,大家有空可以去 查看源码。
- )
- , 11):
- )
- pbar.finish()
- # 60% |######################################################## |
9.colorama
colorama主要用来给文本添加各种颜色,并且非常简单易用。
11.bashplotlib
bashplotlib是一个绘图库,它允许你使用stdin绘制柱状图和散点图等。
- $ pip install bashplotlib
- $ scatter --file data/texas.txt --pch x

[英文原文: 11 Python Libraries You Might Not Know]
哪些 Python 库让你相见恨晚?
Watchdog:Watchdog — watchdog 0.8.0 documentation监视文件系统改动。
Path:API — path.py 5.2 documentation简化文件系统相关操作。
Sphinx 爱上写文档What users say:“Cheers for a great tool that actually makes programmers want to write documentation!”
微信框架:
网络:
爬虫:
- scrapy
- 爬虫:requests + lxml (取代urllib2 + BeautifulSoup)
系统方面:
ORM:
模板引擎:
图像处理:
静态网站生成器
其他:
作为安全界的人。当然要推荐下libmproxy了
from:http://blog.csdn.net/pipisorry/article/details/47185795
ref:TOP 10 PYTHON LIBRARIES OF 2015
python模块 - 常用模块推荐的更多相关文章
- Python一些常用模块
阅读目录 一: collections模块 二: time,datetime模块 三: random模块 四: os模块 五: sys模块 六: json,pickle 七: re正则模块 八:re模 ...
- python的常用模块之collections模块
python的常用模块之collections模块 python全栈开发,模块,collections 认识模块 什么是模块? 常见的场景:一个模块就是一个包含了python定义和声明的文件,文 ...
- Python学习【第6篇】:Python之常用模块1
常用模块一. collocations 模块 时间模块 random模块 os模块 sys模块 序列化模块 re模块 常用模块二:这些模块和面向对象有关 hashlib模块 configparse模块 ...
- python之常用模块篇5
一.日志模块,logging模块 1)logging模块简单使用,屏幕输出.默认级别30 import logging logging.debug( logging.info( logging.war ...
- python基础----常用模块
一 time模块(时间模块)★★★★ 时间表现形式 在Python中,通常有这三种方式来表示时 ...
- python(五)常用模块学习
版权声明:本文为原创文章,允许转载,转载时请务必以超链接形式标明文章 原始出处 .作者信息和本声明. https://blog.csdn.net/fgf00/article/details/52357 ...
- python中常用模块详解二
log模块的讲解 Python 使用logging模块记录日志涉及四个主要类,使用官方文档中的概括最为合适: logger提供了应用程序可以直接使用的接口API: handler将(logger创建的 ...
- python基础--常用模块与面向对象基础
1常用模块 1.1 xml xml是实现不同语言或程序之间进行数据交换的协议 xml的格式如下: <?xml version="1.0"?> <data> ...
- Python编程-常用模块及方法
常用模块介绍 一.time模块 在Python中,通常有这几种方式来表示时间: 时间戳(timestamp):通常来说,时间戳表示的是从1970年1月1日00:00:00开始按秒计算的偏移量.我们运行 ...
随机推荐
- 分布式服务框架Dubbo
随着互联网的发展,网站应用的规模不断扩大,常规的垂直应用架构已无法应对,分布式服务架构以及流动计算架构势在必行,亟需一个治理系统确保架构有条不紊的演进. 单一应用架构 当网站流量很小时,只需一个应用, ...
- MySQL系列教程(二)
mySQL执行计划 语法 explain <sql语句> 例如: explain select * from t3 where id=3952602; explain输出解释 +---- ...
- 安卓高级2 Volley框架的使用案例
初始化类: MyApp.java package qianfeng.com.day37_volley_pull.app; import android.app.Application; import ...
- cassandra 概述
摘要 本篇文章主要是介绍cassandra与其他NoSQL的区别以及自身的特点与应用场景.在关系数据库我们没必要选择数据库,通常需要适配oracle/mysql/sql server/db2 等多种数 ...
- Swift中if与switch语句使用一例
在Swift中相同的条件处理有if和switch两个语句,我们如何取舍呢? 一种情况下我们只在乎x是否在一个范围内,但并不关心x是否穷尽!换句话说不关心在满足范围条件的其他情况下,此时我们可以考虑用i ...
- OpenCV+python 人脸识别
首先给大家推荐一本书:机器学习算法原理与编程实践 本文内容全部转载于书中,相当于一个读书笔记了吧 绪论 1992年麻省理工学院通过实验对比了基于结构特征的方法与基于模版匹配的方法,发现模版匹配的方法要 ...
- UIKit视图动画的微扩展
大熊猫猪·侯佩原创或翻译作品.欢迎转载,转载请注明出处. 如果觉得写的不好请多提意见,如果觉得不错请多多支持点赞.谢谢! hopy ;) 好久没写blog了,还不快快写来- ;] 我们知道在UIKit ...
- android 网络连接 HttpGet HttpPost方法
1.本文主要介绍利用HttpGet和HtppPost方法来获取网络json数据. 代码如下: public HttpData(String Url,HttpGetDataListener listen ...
- JAVA面向对象-----接口的概述
接口的概述 **接口(interface):**usb接口,主要是使用来拓展笔记本的功能,那么在java中的接口主要是使用来拓展定义类的功能,可以弥补java中单继承的缺点. class Pencil ...
- Dynamics CRM 为Visual Studio 2015安装CRM Developer Toolkit
从CRM2015的SDK以后Tools的文件夹里就没有了DeveloperToolkit,而DeveloperToolkit还是停留在VS2012版本,这对于我们这种用新版本的童鞋来说比较头疼,我本地 ...