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'])

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