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开始按秒计算的偏移量.我们运行 ...
随机推荐
- Python教学相关资料
Python教学调查链接 一.专题 1.绘图 如何开始使用Python来画图 Python画图总结 2.科学计算与数据分析 3.可视化 4.网络爬虫 5. 做笔记 Python-Jupyter Not ...
- 两个activity之间透明过渡效果和经验
来看下效果图: 大致效果解释: 1. 当用户点击登录时logo下滑一定距离 2. 下滑后旋转90时 变化图标 3. 继续旋转90度 4. 然后移动到左上角 透明度渐变到上个activity 最后销毁当 ...
- 修改CUSTOM.PLL文件调用客户化FORM&修改标准FORM
修改custom.pll文件里 的过程event:参考例子如下,修改好后上传至$AU_TOP/resource 运行编译frmcmp_batch CUSTOM apps/apps module_typ ...
- Android Stutio中使用java8的Lambda表达式
转载请标明出处: http://blog.csdn.net/xmxkf/article/details/51532028 本文出自:[openXu的博客] 目录: 为什么要使用Lambda表达式 让A ...
- Android开发基础规范(二)
转载请把头部出处链接和尾部二维码一起转载,本文出自逆流的鱼yuiop:http://blog.csdn.net/hejjunlin/article/details/52614696 前言:Androi ...
- actionbar完全解析(一)
Action Bar是一种新増的导航栏功能,在Android 3.0之后加入到系统的API当中,它标识了用户当前操作界面的位置,并提供了额外的用户动作.界面导航等功能.使用ActionBar的好处是, ...
- 字符编码(ASCII、ANSI、GB2312、UTF-8等)系统梳理
引言 在显示器上看见的文字.图片等信息在电脑里面其实并不是我们看见的样子,即使你知道所有信息都存储在硬盘里,把它拆开也看不见里面有任何东西,只有些盘片.假设,你用显微镜把盘片放大,会看见盘片表面凹凸不 ...
- 剑指offer面试题4 替换空格(c)
- gitlab的搭建及问题的解决
gitlab则是类似于github的一个工具,github无法免费建立私有仓库,并且为了代码安全,于是在内网安装了一个自己实验室的一个git服务器,gitlab有很多依赖,而bitnami制作了一键安 ...
- Xcode7.2中如何添加一个Empty Application模板
大熊猫猪·侯佩原创或翻译作品.欢迎转载,转载请注明出处. 如果觉得写的不好请多提意见,如果觉得不错请多多支持点赞.谢谢! hopy ;) Xcode 6.0正式版之后已经没有所谓的Empty Appl ...
