【python】常用内建模块
【datetime】
No1:
獲取當前時間
No2:
時區轉換
>>> from datetime import datetime, timedelta, timezone >>> tz_utc_8 = timezone(timedelta(hours=8)) # 創建時區UTC+8:00 >>> now = datetime.now() >>> now datetime.datetime(2015, 5, 18, 17, 2, 10, 871012) >>> dt = now.replace(tzinfo=tz_utc_8) # 強制設置為UTC+8:00 >>> dt datetime.datetime(2015, 5, 18, 17, 2, 10, 871012, tzinfo=datetime.timezone(datetime.timedelta(0, 28800)))?
# 拿到UTC時間,并強制設置時區為UTC+0:00: >>> utc_dt = datetime.utcnow().replace(tzinfo=timezone.utc) >>> print(utc_dt) 2015-05-18 09:05:12.377316+00:00 # astimezone()將轉換時區為北京時間: >>> bj_dt = utc_dt.astimezone(timezone(timedelta(hours=8))) >>> print(bj_dt) 2015-05-18 17:05:12.377316+08:00 # astimezone()將轉換時區為東京時間: >>> tokyo_dt = utc_dt.astimezone(timezone(timedelta(hours=9))) >>> print(tokyo_dt) 2015-05-18 18:05:12.377316+09:00 # astimezone()將bj_dt轉換時區為東京時間: >>> tokyo_dt2 = bj_dt.astimezone(timezone(timedelta(hours=9))) >>> print(tokyo_dt2) 2015-05-18 18:05:12.377316+09:00【collections】
?No3:
No4:
deque方便插入和刪除
OrderedDict有序
>>> from collections import OrderedDict >>> d = dict([('a', 1), ('b', 2), ('c', 3)]) >>> d # dict的Key是無序的 {'a': 1, 'c': 3, 'b': 2} >>> od = OrderedDict([('a', 1), ('b', 2), ('c', 3)]) >>> od # OrderedDict的Key是有序的 OrderedDict([('a', 1), ('b', 2), ('c', 3)])?
>>> od = OrderedDict() >>> od['z'] = 1 >>> od['y'] = 2 >>> od['x'] = 3 >>> list(od.keys()) # 按照插入的Key的順序返回 ['z', 'y', 'x']?
?FIFO(先進先出)的dict
from collections import OrderedDictclass LastUpdatedOrderedDict(OrderedDict):def __init__(self, capacity):super(LastUpdatedOrderedDict, self).__init__()self._capacity = capacitydef __setitem__(self, key, value):containsKey = 1 if key in self else 0if len(self) - containsKey >= self._capacity:last = self.popitem(last=False)print('remove:', last)if containsKey:del self[key]print('set:', (key, value))else:print('add:', (key, value))OrderedDict.__setitem__(self, key, value)?
?Counter計數器
>>> from collections import Counter >>> c = Counter() >>> for ch in 'programming': ... c[ch] = c[ch] + 1 ... >>> c Counter({'g': 2, 'm': 2, 'r': 2, 'a': 1, 'i': 1, 'o': 1, 'n': 1, 'p': 1})【base64】
No5:
Base64是一種用64個字符來表示任意二進制數據的方法。
>>> import base64 >>> base64.b64encode(b'binary\x00string') b'YmluYXJ5AHN0cmluZw==' >>> base64.b64decode(b'YmluYXJ5AHN0cmluZw==') b'binary\x00string'?
>>> base64.b64encode(b'i\xb7\x1d\xfb\xef\xff') b'abcd++//' >>> base64.urlsafe_b64encode(b'i\xb7\x1d\xfb\xef\xff') b'abcd--__' >>> base64.urlsafe_b64decode('abcd--__') b'i\xb7\x1d\xfb\xef\xff'No6:
【struct】
pack的第一個參數是處理指令,'>I'的意思是:
>表示字節順序是big-endian,也就是網絡序,I表示4字節無符號整數。
?【摘要算法】
No7:
摘要算法又稱哈希算法、散列算法。它通過一個函數,把任意長度的數據轉換為一個長度固定的數據串(通常用16進制的字符串表示)
?
No8:
【hmac】
No9:
【itertools】迭代
count()
>>> import itertools >>> natuals = itertools.count(1) >>> for n in natuals: ... print(n) ...數字無限增長,差點沒爆掉
cycle()
>>> import itertools >>> cs = itertools.cycle('ABC') # 注意字符串也是序列的一種 >>> for c in cs: ... print(c) ...ABC無限重復,又差點沒爆掉
repeat()--限定重復次數
chain()--可以把一組迭代對象串聯起來,形成一個更大的迭代器:
groupby()--把迭代器中相鄰的重復元素挑出來放在一起:
?
?
No10:
try:f = open('/path/to/file', 'r')f.read() finally:if f:f.close()可簡化為
with open('/path/to/file', 'r') as f:f.read()No11:
class Query(object):def __init__(self, name):self.name = namedef __enter__(self):print('Begin')return selfdef __exit__(self, exc_type, exc_value, traceback):if exc_type:print('Error')else:print('End')def query(self):print('Query info about %s...' % self.name)使用
with Query('Bob') as q:q.query()》》》》類可簡化為
from contextlib import contextmanagerclass Query(object):def __init__(self, name):self.name = namedef query(self):print('Query info about %s...' % self.name)@contextmanager def create_query(name):print('Begin')q = Query(name)yield qprint('End')使用
with create_query('Bob') as q:q.query()No12:
No13:
from contextlib import closing from urllib.request import urlopenwith closing(urlopen('https://www.python.org')) as page:for line in page:print(line)結果居然打印出整個html界面的代碼
【GET】
No14:
from urllib import requestreq = request.Request('http://www.douban.com/') req.add_header('User-Agent', 'Mozilla/6.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/8.0 Mobile/10A5376e Safari/8536.25') with request.urlopen(req) as f:print('Status:', f.status, f.reason)for k, v in f.getheaders():print('%s: %s' % (k, v))print('Data:', f.read().decode('utf-8'))結果會返回豆瓣網的移動端頁面
No15:
【POST】
模擬微博登陸
from urllib import request, parseprint('Login to weibo.cn...') email = input('Email: ') passwd = input('Password: ') login_data = parse.urlencode([('username', email),('password', passwd),('entry', 'mweibo'),('client_id', ''),('savestate', '1'),('ec', ''),('pagerefer', 'https://passport.weibo.cn/signin/welcome?entry=mweibo&r=http%3A%2F%2Fm.weibo.cn%2F') ])req = request.Request('https://passport.weibo.cn/sso/login') req.add_header('Origin', 'https://passport.weibo.cn') req.add_header('User-Agent', 'Mozilla/6.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/8.0 Mobile/10A5376e Safari/8536.25') req.add_header('Referer', 'https://passport.weibo.cn/signin/login?entry=mweibo&res=wel&wm=3349&r=http%3A%2F%2Fm.weibo.cn%2F')with request.urlopen(req, data=login_data.encode('utf-8')) as f:print('Status:', f.status, f.reason)for k, v in f.getheaders():print('%s: %s' % (k, v))print('Data:', f.read().decode('utf-8'))No16:
【Handler】
proxy_handler = urllib.request.ProxyHandler({'http': 'http://www.example.com:3128/'}) proxy_auth_handler = urllib.request.ProxyBasicAuthHandler() proxy_auth_handler.add_password('realm', 'host', 'username', 'password') opener = urllib.request.build_opener(proxy_handler, proxy_auth_handler) with opener.open('http://www.example.com/login.html') as f:passNo17:
【XML】
操作XML有兩種方法:DOM和SAX。DOM會把整個XML讀入內存,解析為樹,因此占用內存大,解析慢,優點是可以任意遍歷樹的節點。SAX是流模式,邊讀邊解析,占用內存小,解析快,缺點是我們需要自己處理事件。
正常情況下,優先考慮SAX,因為DOM實在太占內存。
from xml.parsers.expat import ParserCreateclass DefaultSaxHandler(object):def start_element(self, name, attrs):print('sax:start_element: %s, attrs: %s' % (name, str(attrs)))def end_element(self, name):print('sax:end_element: %s' % name)def char_data(self, text):print('sax:char_data: %s' % text)xml = r'''<?xml version="1.0"?> <ol><li><a href="/python">Python</a></li><li><a href="/ruby">Ruby</a></li> </ol> '''handler = DefaultSaxHandler() parser = ParserCreate() parser.StartElementHandler = handler.start_element parser.EndElementHandler = handler.end_element parser.CharacterDataHandler = handler.char_data parser.Parse(xml) L = [] L.append(r'<?xml version="1.0"?>') L.append(r'<root>') L.append(encode('some & data')) L.append(r'</root>') return ''.join(L)No18:
【HTMLParser】
from html.parser import HTMLParser from html.entities import name2codepointclass MyHTMLParser(HTMLParser):def handle_starttag(self, tag, attrs):print('<%s>' % tag)def handle_endtag(self, tag):print('</%s>' % tag)def handle_startendtag(self, tag, attrs):print('<%s/>' % tag)def handle_data(self, data):print(data)def handle_comment(self, data):print('<!--', data, '-->')def handle_entityref(self, name):print('&%s;' % name)def handle_charref(self, name):print('&#%s;' % name)parser = MyHTMLParser() parser.feed('''<html> <head></head> <body> <!-- test html parser --><p>Some <a href=\"#\">html</a> HTML tutorial...<br>END</p> </body></html>''')?
總結
以上是生活随笔為你收集整理的【python】常用内建模块的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 异步加载
- 下一篇: 计算机基本概念及简单的二进制运算