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框架应用之(三)--Zookeeper注册中心、管理控制台的安装及讲解
我是在linux下使用dubbo-2.3.3以上版本的zookeeper注册中心客户端.Zookeeper是Apache Hadoop的子项目,强度相对较好,建议生产环境使用该注册中心.Dubbo未对 ...
- 计算机网络之域名系统DNS
域名系统DNS 域名系统DNS(Domai NameSystem)是因特网使用的命名系统,用于把便于人们使用的机器名字转换为IP地址. 许多应用层软件经常直接使用域名系统,但计算机的用户只是间接而不是 ...
- java自动装箱拆箱总结
对于java1.5引入的自动装箱拆箱,之前只是知道一点点,最近在看一篇博客时发现自己对自动装箱拆箱这个特性了解的太少了,所以今天研究了下这个特性.以下是结合测试代码进行的总结. 测试代码: int a ...
- Android捕获全局异常
Android捕获全局异常 程序避免不了出现bug,导致程序崩溃,为了尽量不影响用户体验,可以全局捕获异常 效果图 异常捕获处理前 异常捕获处理后(将程序重新启动) 捕获异常的工具类 package ...
- Dynamics CRM2016 Web API之创建记录
前篇介绍了通过primary key来查询记录,那query的知识点里面还有很多需要学习的,这个有待后面挖掘,本篇来简单介绍下用web api的创建记录. 直接上代码,这里的entity的属性我列了几 ...
- 操作系统服务:OS模块
http://blog.csdn.net/pipisorry/article/details/52454486 一般的操作系统服务之OS模块Generic Operating System Servi ...
- Xcode8之后,苹果列出了最新App被拒十大原因
开发者在开发应用程序之前,熟悉苹果审核应用的技术.内容以及设计准则是非常重要的,可以大大降低应用审核被拒的可能性. 最近,苹果通过一个专门的页面给出了截止2016年10月10日应用提交审核被拒的十大原 ...
- mysql进阶(二十八)MySQL GRANT REVOKE用法
mysql进阶(二十八)MySQL GRANT REVOKE用法 MySQL的权限系统围绕着两个概念: 认证->确定用户是否允许连接数据库服务器: 授权->确定用户是否拥有足够的权限执 ...
- 乐观的并发策略——基于CAS的自旋
悲观者与乐观者的做事方式完全不一样,悲观者的人生观是一件事情我必须要百分之百完全控制才会去做,否则就认为这件事情一定会出问题:而乐观者的人生观则相反,凡事不管最终结果如何,他都会先尝试去做,大不了最后 ...
- Android动态换肤(一、应用内置多套皮肤)
动态换肤在很多android应用中都有使用,用户根据自己的喜好设置皮肤主题,可以增强用户使用应用的舒适度. Android换肤可以分为很多种,它们从使用方式,用户体验以及项目框架设计上体现了明显的差异 ...
