python實用技巧任務切分


今天來說說,Python中的任務切分。以爬蟲爲例,從一個存 url 的 txt 文件中,讀取其內容,我們會獲取一個 url 列表。我們把這一個 url 列表稱爲大任務。


列表切分
在不考慮內存佔用的情況下,我們對上面的大任務進行一個切分。比如我們將大任務切分成的小任務是每秒最多隻訪問5個URL。
import os 
import time 
CURRENT_DIR = os.path.dirname(os.path.abspath(__file__)) 
def read_file(): 
file_path = os.path.join(CURRENT_DIR, "url_list.txt") 
with open(file_path, "r", encoding="utf-8") as fs: 
result = [i.strip() for i in fs.readlines()] return result 
def fetch(url): 
print(url) 
def run(): 
max_count = 5 
url_list = read_file() 
for index in range(0, len(url_list), max_count): 
start = time.time() fetch(url_list[index:index + max_count]) end = time.time() - start 
if end < 1: 
time.sleep(1 - end) 
if __name__ == '__main__': 
run() 

快速學習python基礎
http://www.makeru.com.cn/live/5286_1688.html?s=148349
關鍵代碼都在for循環裏,首先我們通過聲明range的第三個參數,該參數指定迭代的步長爲5,這樣每次index增加都是以5爲基數,即0,5,10。。。
然後我們對url_list做切片,每次取其五個元素,這五個元素會隨着index的增加不斷的在改變,如果最後不夠五個了,按照切片的特性這個時候就會有多少取多少了,不會造成索引超下標的問題   

python 人工智能-神經網絡
http://www.makeru.com.cn/live/5020_1669.html?s=148349

入門爬蟲數據提取 http://www.makeru.com.cn/live/5286_1689.html?s=148349