python模块 - 常用模块推荐

news/2024/7/19 9:11:39 标签: 数据库, 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">
[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处理器:

python">
>>> 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

一个文件系统处理库,不过目前还在开发阶段

python">
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, 接口很漂亮:

python">
# 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) :)

python">
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的语法来进行查询,可以使查询语句变得简洁,灵活,而且漂亮。

例如可以使用如下的语句来进行一个查询:

python">
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的作者编写的,一个数据格式检查库,非常新颖:

python">
>>> 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的函数式编程:

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:

python">
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文件:

python">
autopep8 -i mycode.py

kachayev/fn.py

fn.py : Functional programming in Python: implementation of missing features to enjoy FP

这是个很有趣的项目,来弥补Python在函数式编程方面没有的一些特性。来看个sample:

python">
from fn import _
assert list(map(_ * 2, range(5))) == [0,2,4,6,8] 
python-patterns" class="section">

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 在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 plain copy 在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 plain copy 在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 plain copy 在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 plain copy 在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 plain copy 在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 plain copy 在CODE上查看代码片 派生到我的代码片
 
 
  1. $ pip install bashplotlib  
  2. $ scatter --file data/texas.txt --pch x  

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

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

 

 

哪些 Python 库让你相见恨晚?

Watchdog:pythonhosted.org/watchdog/">Watchdog — watchdog 0.8.0 documentation监视文件系统改动。

Path:pythonhosted.org/path.py/api.html">API — path.py 5.2 documentation简化文件系统相关操作。

 

 

转载于:https://www.cnblogs.com/xuaijun/p/8006529.html


http://www.niftyadmin.cn/n/539681.html

相关文章

java 验证码 计算题中有中文 实例_详解java图形验证码生成工具类web页面校验验证码的代码案例...

这篇文章主要为大家详细介绍了java图形验证码生成工具类&#xff0c;web页面校验验证码&#xff0c;具有一定的参考价值&#xff0c;感兴趣的小伙伴们可以参考一下最近做验证码&#xff0c;参考网上案例&#xff0c;发现有不少问题&#xff0c;特意进行了修改和完善。验证码生成…

js和php的区别,php和js区别

1、PHP拼字符串用的是点&#xff0c;js用号。2、php文件要放在wamp文件里面的www里面。3、php与js的嵌入方式相同&#xff0c;只是嵌入的标记不一样。4、php输出语法用echo。可以输出多个字符串。特殊的输出方法 var_dump()。5、PHP定义变量用的是$。6、php特殊的定义方式$变量…

理解 Linux 的硬链接与软链接

原出处&#xff1a; https://www.ibm.com/developerworks/cn/linux/l-cn-hardandsymb-links/index.html 这篇博客很清楚讲了&#xff0c;linux软连接和硬链接的区别&#xff0c;很好懂 尤其是图很赞&#xff0c;简单直观 ----------------------------------------------------…

php中声明一个数组,php中如何创建一个array数组呢?

摘要:下文讲述php中创建数组array的方法分享&#xff0c;如下所示&#xff1b;实现思路:php中创建数组需使用array()函数进行创建php创建数组的语法:方式1:array(value1,value2,value3,etc.);------参数说明-----value1,value2,value3 ...:为数组中数组值方式2&#xff1a;arra…

难度2:素数距离问题

描述 现在给出你一些数&#xff0c;要求你写出一个程序&#xff0c;输出这些整数相邻最近的素数&#xff0c;并输出其相距长度。如果左右有等距离长度素数&#xff0c;则输出左侧的值及相应距离。 如果输入的整数本身就是素数&#xff0c;则输出该素数本身&#xff0c;距离输出…

php获取指定url请求头,【PHP】获取浏览器HTTP请求header信息、获取服务器HTTP响应header信息...

一、认识HTTPHTTP协议历史及设计思路(点击浏览)二、获取浏览器HTTP请求header信息1. Apach服务器下可以直接使用 PHP自带函数获取客户端HTTP请求头信息/*作用&#xff1a;获取客户端HTTP请求所有头信息(header)参数&#xff1a;无。返回&#xff1a;HTTP请求所有头信息数组*/ge…

Mvc5中使用Js嵌入资源访问

有些项目在一些特殊场景下会把Js文件作为嵌入资源打包进dll中 网上各种搜索都没有解决方案。 后来琢磨的时候发现。。。 ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓ 1. 设置js文件为嵌入资源 2. 读取内嵌的资源文件&#xff08;js文件&#xff09;为FileStre…

zabbix setup.php出错,zabbix安装setup界面常见错误处理

错误1、zabbix/setup.php was not found on this serve提示如上错误大致有以下几个原因&#xff1a;原因一&#xff1a;是否安装了apache&#xff0c;以便解析html解决办法&#xff1a;安装apache原因二&#xff1a;php可能没有完全安装好解决办法&#xff1a;重新编译安装或是…