Python常用模块

python的函数使用帮助可以通过help()函数来查看,输出的是官方的文档说明及实例

1.序列化模块:

    1)json,pickle:①dumps:将字典,列表等转化为字典,列表字符串;②loads:将字典,列表,JSON字符串等转化为字典,列表格式;③dump:将基本数据类型转化成python语言能识别的字符串,并保存到文件;④load:从文件中读取序列化保存到文件中的python基本数据类型(经测试json此方法貌似不可用了);

# -*- coding: utf-8 -*-

import json,pickle

dict1 = {'user':'john','sex':'male'}  
str1 = json.dumps(dict1)
str2 = pickle.dumps(dict1)

print str1,type(str1)
print str2,type(str2)
print json.loads(str1),type(json.loads(str1))
print pickle.loads(str2),type(pickle.loads(str2))
# -*- coding: utf-8 -*-

import json,pickle

str1 = {'user':'john','sex':'male'}

print '-------------json--------------'
with open('test.json','w') as fout:
    json.dump(str1,fout)
    fout.close()

with open('test.json','r') as fin:
    print fin.readline(),type(fin.readline())
    print 'fin.read():',fin.read()
    # print json.load(fin)  #查看源码里面调用了fp 的read()方法,当时read()出来的是空,所以会报No JSON object could be decoded的错
    fin.close()

print '-------------pickle--------------'
with open('test.pk','w') as pout:
    pickle.dump(str1,pout)

with open('test.pk','r') as pin:
    print pickle.load(pin)

2.时间模块:

    1)datetime,time
# -*- coding: utf-8 -*-

import datetime,time

date1 = "2018-05-03 12:00:00"

# 添加8小时
date2 = datetime.datetime.strptime(date1,'%Y-%m-%d %H:%M:%S')+datetime.timedelta(hours=8)
print date2

# 添加2天
date3 = datetime.datetime.strptime(date1,'%Y-%m-%d %H:%M:%S')+datetime.timedelta(days=2)
print date3

#获得时间
print datetime.datetime.now()	#获得时分秒
print datetime.date.today()	#获得天
print time.time()		#获得秒

3.日志模块:

    1)logging:打印日志,会生成一个日志文件
# -*- coding: utf-8 -*-

import logging

logging.basicConfig(
    filename='log.log',
    format='%(asctime)s - %(name)s - %(levelname)s -%(module)s:  %(message)s',
    datefmt='%Y-%m-%d %H:%M:%S %p',
    level=10)
  
logging.debug('debug')
logging.info('info')
logging.warning('warning')
logging.error('error')
logging.critical('critical')
logging.log(10,'log')

4.性能测试:

    1)cProfile:输出python程序所消耗的时间,

# -*- coding: utf-8 -*-

import cProfile

def run_range():
    count = 0
    for i in range(0,100000):
        count = count + i
    return count

def run_xrange():
    count = 0
    for i in xrange(0,100000):
        count = count + i
    return count

run_range()   #必须调用才会输出其所消耗时间
run_xrange()

print '------------------'
# 直接把分析结果打印到控制台
#python -m cProfile test.py
# 把分析结果保存到文件中
#python -m cProfile -o result.out test.py
# 增加排序方式
#python -m cProfile -o result.out -s cumulative test.py

    2)pstats:cProfile分析的结果可以输出到指定的文件中,但是文件内容是以二进制的方式保存的,用文本编辑器打开时乱码。所以,Python提供了一个pstats模块,用来分析cProfile输出的文件内容

# -*- coding: utf-8 -*-

import cProfile,pstats

def run_range():
    count = 0
    for i in range(0,100000):
        count = count + i
    return count

cProfile.run("run_range()", filename="result.out")

p = pstats.Stats("result.out")
p.strip_dirs().sort_stats(-1).print_stats()

    3)timeit:轻量级的测试模块,输出单个函数或者表达式的所耗时间

# -*- coding: utf-8 -*-

import timeit

def run_range():
    count = 0
    for i in range(0,100000):
        count = count + i
    return count

print timeit.timeit(stmt=run_range, number=1)
print timeit.timeit(stmt=run_range, number=10)

5.网络请求:

    1)requests:参考地址:http://docs.python-requests.org/zh_CN/latest/user/quickstart.html

6.迭代器:

    1)itertools:用于创建自定义的迭代器,itertools 提供的工具相当高效且节省内存;参考(https://blog.csdn.net/c465869935/article/details/51598388)

# -*- coding: utf-8 -*-

from itertools import count,cycle,repeat,chain,compress,ifilter,ifilterfalse
from itertools import takewhile,imap,izip,izip_longest,product,groupby

its=["a","b","c","d"]

print '-----------count---------'
# count(start, step);start开头,step步长;无限循环
for item in count(1,3):
    if item > 10:
        break
    print item

print '-----------cycle---------'
# cycle(iterable);iterable 为可迭代对象;无限循环
for item in cycle(its):
    print item
    if item == 'c':
        break

print '-----------repeat---------'
# repeat(object[, times]);object为可迭代对象,times为迭代次数,默认为无限次
for item in repeat(its,3):
    print item

print '-----------chain---------'
# chain(*iterables);*iterables为一个或多个可迭代序列
hers=["A","B","C","D"]
others=["1","2","3","4"]
for item in chain(its,hers,others):
    print item

print '-----------compress---------'
# compress(data, selectors);data为数据对象,selectors为选择器(规则);返回数据对象中对应规则为True的元素
selector=[True,False,1,0,3,False,-2,"y"]
for item in compress(its,selector):
    print item

print '-----------ifilter---------'
# ifilter(predicate, iterable);过滤当断言为真的返回
for item in ifilter(lambda x:x/3,range(6)):
    print item

print '\n'

for item in ifilterfalse(lambda x:x-3,range(6)):
    print item

print '-----------takewhile---------'
# takewhile(predicate, iterable);一旦可迭代对象的断言或过滤器结果为 True 就返回元素
for item in takewhile(lambda x: x<5, [1,4,6,4,1]):
    print item

print '-----------imap---------'
# imap(function, *iterables);function为功能函数;*iterables为可迭代序列;返回迭代序列中每个元素被功能函数执行后的值
digi=[1,2,0]
for item in imap(lambda x:x+3,digi):
    print item

print '-----------izip---------'
# izip(*iterables);*iterables为一个或多个可迭代对象;返回所有可迭代对象的迭代器(止于最短序列)
digi=[1,2,0]
hers=["A","B","C","D"]
for item in izip(hers,digi):
    print item
print "\n"
for item in izip(digi,hers):
    print item

print '-----------izip_longest---------'
# izip_longest则与izip有点相反的味道(止于最长序列);没有的用None代替
for item in izip_longest(hers,digi):
    print item

print '-----------product---------'
# product(*iterables[, repeat]);*iterables为迭代器(对象);repeat为迭代次数,默认为1
digi=[1,2]
hers=["A"]
for item in product(digi,repeat=2):
    print item
print "\n"
for item in product(digi,hers):
    print item
print "\n"
for item in product(digi,hers,repeat=2):
    print item

print '-----------groupby---------'
# groupby(*iterables[, func]);迭代器中相邻的重复元素挑出来放在一起
for key, group in groupby('AAABBBCCAAA'):
    print key, list(group)

# 不区分大小写
for key, group in groupby('AaaBBbcCAAa', lambda c: c.upper()):
    print key, list(group)

7.函数模块:

    1)functools:用于高阶函数:指那些作用于函数或者返回其它函数的函数,通常只要是可以被当做函数调用的对象就是这个模块的目标;参考(http://www.cnblogs.com/zhbzz2007/p/6001827.html)

# -*- coding: utf-8 -*-

import functools

print '----------cmp_to_key----------'
# cmp_to_key,将一个比较函数转换关键字函数
# 递增:ele1 - ele2;递减:ele2 - ele1;不变:ele1 + ele2
def compare(ele1,ele2):
    return ele1 - ele2

a = [2,3,1]
print sorted(a, key = functools.cmp_to_key(compare))

print '----------partial----------'
# functools.partial(func, *args, **keywords),函数装饰器,返回一个新的partial对象
def add(a,b):
    return a + b

add3 = functools.partial(add,3)
add5 = functools.partial(add,5)
print add3(4)
print add5(10)

print '----------reduce----------'
# 与Python内置的reduce函数一样
a = range(1,6)
print functools.reduce(lambda x,y:x+y,a)

print '----------wraps----------'
# wraps,可用作一个装饰器;保留原函数的所有信息
def my_decorator(f):
    @functools.wraps(f)
    def wrapper(*args,**kwds):
        print "Calling decorated function"
        return f(*args,**kwds)
    return wrapper

@my_decorator
def example():
    """DocString"""
    print "Called example function"

example()
print example.__name__
print example.__doc__

8.加密模块:

    1)hashlib:用于加密相关的操作,代替了md5模块和sha模块,主要提供 SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 算法

# -*- coding: utf-8 -*-

import hashlib,hmac

print '-----------md5------------'
hash = hashlib.md5()
hash.update('admin')
print hash.hexdigest()
print '\n'
# 对加密算法中添加自定义key再来做加密
hash = hashlib.md5('fandebiao')
hash.update('admin')
print hash.hexdigest()

print '-----------hmac------------'
# hmac模块,它内部对我们创建key和内容再进行处理然后再加密
h = hmac.new('fandebiao')
h.update('admin')
print h.hexdigest()

print '-----------sha1------------'
hash = hashlib.sha1()
hash.update('admin')
print hash.hexdigest()

print '-----------sha256------------'
hash = hashlib.sha256()
hash.update('admin')
print hash.hexdigest()

print '-----------sha384------------'
hash = hashlib.sha384()
hash.update('admin')
print hash.hexdigest()

print '-----------sha512------------'
hash = hashlib.sha512()
hash.update('admin')
print hash.hexdigest()

9.随机数:

    1)random:生成随机数

# -*- coding: utf-8 -*-

import random

print '-------------random------------'
print random.random() # 0~1之间的随机数,保留小数后面12位;没有参数

print '------------randomint----------'
print random.randint(2,2)
print random.randint(2,3) # 2<= n <=3的整数;两个参数后边的必须大于等于前面的

print '------------randrange----------'
print random.randrange(1,2) # 1<= n <2的整数;后面的必须比前面的数大
print random.randrange(1,10,3) # 1<= n <10 步长为3的列表中随机一个整数;

print '------------uniform------------'
print random.uniform(1,1) # 浮点数
print random.uniform(1,2)

print '------------sample------------'
print random.sample('abcdefghij',3) # 返回的是随机3个数组成的列表

print '------------choice------------'
print random.choice(['apple', 'pear', 'peach', 'orange', 'lemon'])

print '------------shuffle------------'
items = [1, 2, 3, 4, 5, 6]
random.shuffle(items) # 洗牌,返回值为None
print items

10.sys模块:

# -*- coding: utf-8 -*-

import sys

print sys.argv      	# 命令行参数List,第一个元素是程序本身路径
print sys.version      	# 获取Python解释程序的版本信息
print sys.platform      # 返回操作系统平台名称
print sys.path          # 返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值
print sys.maxint        # 最大的Int值
print sys.exit(n)       # 退出程序,正常退出时exit(0)

11.os模块:

# -*- coding: utf-8 -*-

import os

print os.getcwd()                           # 获取当前工作目录,即当前python脚本工作的目录路径
print os.listdir('dirname')                 # 列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印
print os.curdir                             # 返回当前目录: ('.')
print os.makedirs('dirname1/dirname2')      # 可生成多层递归目录
print os.removedirs('dirname1')             # 若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推
print os.mkdir('dirname')                   # 生成单级目录;相当于shell中mkdir dirname
print os.rmdir('dirname')                   # 删除单级空目录,若目录不为空则无法删除,报错;相当于shell中rmdir dirname
print os.path.exists(path)                  # 如果path存在,返回True;如果path不存在,返回False
print os.path.isabs(path)                   # 如果path是绝对路径,返回True
print os.path.isfile(path)                  # 如果path是一个存在的文件,返回True。否则返回False
print os.path.isdir(path)                   # 如果path是一个存在的目录,则返回True。否则返回False
print os.path.join(path1[, path2[, ...]])   # 将多个路径组合后返回,第一个绝对路径之前的参数将被忽略
print os.path.getatime(path)                # 返回path所指向的文件或者目录的最后存取时间
print os.path.getmtime(path)                # 返回path所指向的文件或者目录的最后修改时间
print os.path.split(os.getcwd())            # 将path分割成目录和文件名二元组返回
print os.environ                            # 获取系统环境变量
print os.name                               # 输出字符串指示当前使用平台;win->'nt'; Linux->'posix'

12.re模块:

# -*- coding: utf-8 -*-

import re

line = "Cats are smarter than dogs"
matchObj = re.match( r'(.*) are (.*?) .*', line, re.M|re.I)
if matchObj:
   print "matchObj.group() : ", matchObj.group()
   print "matchObj.group(1) : ", matchObj.group(1)
   print "matchObj.group(2) : ", matchObj.group(2)
else:
   print "No match!!"

# 查找文件中的大写字母
count = 0
with open('log.log') as f:
    content = f.readline()
    while content:
        big = re.findall(r'[A-Z]',content)
        print big
        count = count + len(big)
        content = f.readline()
print count

# span:返回匹配数组,group:返回匹配字符串
print re.match(r'www', 'www.runoob.com').span()    # 在起始位置匹配
print re.match(r'www', 'www.runoob.com').group()   # 在起始位置匹配
print re.match(r'com', 'www.runoob.com')           # 不在起始位置匹配

# 匹配相应数字
it1 = re.finditer(r"\d+","12a32bc43jf3") 
for match in it1: 
    print match.group()
it2 = re.finditer(r"\d{1}","12a32bc43jf3") 
for match in it2: 
    print match.group()
it3 = re.finditer(r"\d{2}","12a32bc43jf3") 
for match in it3: 
    print match.group()

13.excel文件读写:

    1)csv:对csv文件进行读写操作

# -*- coding: utf-8 -*-

import csv

fname = 'testcsv.csv'
# 解决写入空行问题 使用wb不会再每一行后面插入空行
with open(fname, 'wb') as csvfile:
    csvwriter = csv.writer(csvfile,delimiter=',')
    lst= [[1,2,3],[4,5,6]]
    for item in lst:
        csvwriter.writerow(item)

# 读取操作
with open(fname,'r') as csvfile:
    rows = csv.reader(csvfile)
    for row in rows:
        print row
        print type(row) # 类型为一个list

# 字典写入
with open('names.csv', 'w') as csvfile:
    fieldnames = ['first_name', 'last_name']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    writer.writeheader()
    writer.writerow({'first_name': 'Baked', 'last_name': 'Beans'})
    writer.writerow({'first_name': 'Lovely', 'last_name': 'Spam'})
    writer.writerow({'first_name': 'Wonderful', 'last_name': 'Spam'})

# 字典读取
with open('names.csv') as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        print(row['first_name'], row['last_name'])

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章