|
4 | 4 | import base64
|
5 | 5 | import hashlib
|
6 | 6 | import hmac
|
| 7 | +import itertools |
7 | 8 | import os
|
8 | 9 | from collections import ChainMap
|
9 | 10 | from collections import Counter
|
10 | 11 | from collections import OrderedDict
|
11 | 12 | from collections import defaultdict
|
12 | 13 | from collections import deque
|
13 | 14 | from collections import namedtuple
|
| 15 | +from contextlib import closing |
| 16 | +from contextlib import contextmanager |
14 | 17 | from datetime import datetime
|
| 18 | +from urllib.request import urlopen |
15 | 19 |
|
16 | 20 | # =======================获取当前日期和时间=======================================
|
17 | 21 |
|
|
83 | 87 | sha2.update('test sha256'.encode('utf-8'))
|
84 | 88 | print(sha2.hexdigest())
|
85 | 89 | print(hmac.new(b'salt', b'hello dear', digestmod='md5').hexdigest())
|
| 90 | + |
| 91 | +# =======================================================迭代工具================================================ |
| 92 | + |
| 93 | +# 如果没有重复次数,将无限重复下去 |
| 94 | +bs = itertools.repeat('a', 8) |
| 95 | +for b in bs: |
| 96 | + print(b) |
| 97 | +# 把一组迭代对象串联起来 |
| 98 | +bs = itertools.chain('abc', 'def') |
| 99 | +for b in bs: |
| 100 | + print(b) |
| 101 | +# 把迭代器中相邻的重复元素挑出来放在一起 |
| 102 | +for k, g in itertools.groupby('aaabbbccaa'): |
| 103 | + print(k, list(g)) |
| 104 | + |
| 105 | + |
| 106 | +# 更多应用,请参考: |
| 107 | +# https://www.liaoxuefeng.com/wiki/1016959663602400/1017783145987360 |
| 108 | + |
| 109 | +# ===========================================================上下文管理================================================ |
| 110 | + |
| 111 | +class Query(object): |
| 112 | + |
| 113 | + def __init__(self, name: str): |
| 114 | + self.name = name |
| 115 | + |
| 116 | + def query(self): |
| 117 | + print('query about %s' % self.name) |
| 118 | + |
| 119 | + |
| 120 | +@contextmanager |
| 121 | +def create_query(name: str) -> Query: |
| 122 | + print('begin') |
| 123 | + q = Query(name) |
| 124 | + yield q |
| 125 | + print('end') |
| 126 | + |
| 127 | + |
| 128 | +# 实现了上下文管理的对象,可以使用with语句来实现自动关闭资源 |
| 129 | +with create_query('bob') as q: |
| 130 | + q.query() |
| 131 | +# 没有实现上下文管理的,可以用closing来实现 |
| 132 | +with closing(urlopen('https://www.python.org')) as page: |
| 133 | + for line in page: |
| 134 | + print(line) |
0 commit comments