《Python編程快速上手—讓繁瑣工作自動化》第15章實踐項目答案

15.3 項目:超級秒表

項目要求:自己用 Python 寫一個簡單的秒表程序

#! python3
# A simple stopwatch program.

import time

print('Press ENTER to begin. Afterwards, press ENTER to "click" the stopwatch. Press Ctrl-C to quit.')
input()
print('Started.')
startTime = time.time()
lastTime = startTime
lapNum = 1

try:
    while True:
        input()
        laptime = round((time.time() - lastTime), 2)
        totalTime = round((time.time() - startTime), 2)
        print('Lap: %s; laptime: %s; totalTime: %s' % (lapNum, laptime, totalTime), end=' ')
        lapNum += 1
        lastTime = time.time()
except KeyboardInterrupt:
    print('\nDONE!')
    input('click any key to exit')

15.7 項目:多線程 XKCD 下載程序

項目要求:多線程程序中有一些線程在下載漫畫,同時另一些線程在建立連接,或?qū)⒙媹D像文件寫入硬盤。它更有效地使用 Internet 連接,更迅速地下載這些漫畫。打開一個新的文件編輯器窗口,并保存為 multidownloadXkcd.py。你將修改這個程序,添加多線程。

#! python3
# Downloads XKCD comics using multiple threads.

import os, bs4, requests
urls = 'http://xkcd.com'
os.makedirs('xkcd', exist_ok = True)
def comic_download_kxcd(startComic, endComic):
    for num in range(startComic, endComic):
    # todo: download the page
        url = urls + '/%s/' % num
        print('Downloading page %s...' % url)
        res = requests.get(url)
        try:
            res.raise_for_status()
        except requests.exceptions.HTTPError:
            pass
        soup = bs4.BeautifulSoup(res.text, "html.parser")

    # todo: find the url of comic page
        comicElems = soup.select('#comic img')
        if comicElems == []:
            print('Could not find comic image!')
        else:
            comicUrl = 'http:' + comicElems[0].get('src')
    # todo: download the jpg
            print('Downloading image %s' % comicUrl)
            res = requests.get(comicUrl)
            res.raise_for_status()
    # todo: save jpg to ./xkcd
            image_name = os.path.join('xkcd', os.path.basename(comicUrl))
            with open(image_name, 'wb') as imageFile:
                for chunk in res.iter_content(100000):
                    imageFile.write(chunk)
    # todo: get the prev button's url
        prevLink = soup.select('a[rel="prev"]')[0]

# Create and start the Thread objects.
import threading
comic_threads = []
for i in range(1,1400,100):      # loops 14 times, creates 14 threads
    comic_thread = threading.Thread(target=comic_download_kxcd, args=(i, i+5)) 
    comic_threads.append(comic_thread)
    comic_thread.start()

# Wait for all threads to end.
for comic_thread in comic_threads:
    comic_thread.join()

print('Done.')

思路:

  1. 多線程這個真的很驚艷,第一次接觸會覺得“居然還有這種操作?!”
  2. 按照書中步驟一步步碼

15.9 項目:簡單的倒計時程序

項目要求:讓我們來寫一個倒計時程序,在倒計時結(jié)束時報警。

#! python3
# A simple countdown script.

import time, subprocess
while True:
    try:
        time_l = int(input('Please input a time(seconds): '))
    except Exception:
        print('number please!')
    else:
        break

while time_l > 0:
    print(time_l)       # 不知道為什么這里傳入end=" "會不顯示數(shù)字進行倒計時
    time.sleep(1)
    time_l = time_l - 1

print('\nalert!!')
time.sleep(2)
a = subprocess.Popen(['start','abc001.txt'], shell=True)

15.12.1 實踐項目:美化的秒表

項目要求:擴展本章的秒表項目,讓它利用 rjust()和 ljust()字符串方法“美化”的輸出。

#! python3
# A simple stopwatch program.

import time

print('Press ENTER to begin. Afterwards, press ENTER to "click" the stopwatch. Press Ctrl-C to quit.')
input()
print('Started.')
startTime = time.time()
lastTime = startTime
lapNum = 1

try:
    while True:
        input()
        laptime = round((time.time() - lastTime), 2)
        totalTime = round((time.time() - startTime), 2)
        print('Lap #' + str(lapNum).rjust(2) + ':' + ('%.2f'%totalTime).rjust(6) + 
        ' (' + ('%.2f'%laptime).rjust(5) +  ')',end=' ')
        lapNum += 1
        lastTime = time.time()
except KeyboardInterrupt:
    print('\nDONE!')
    input('click any key to exit')

15.12.2 實踐項目:計劃的 Web 漫畫下載

  • 容我偷個懶

環(huán)境:python3

想做這個系列文章,就是因為當時看這本書時,想看看網(wǎng)上有沒更優(yōu)美的解決,但是略難找到。所以就把自己的項目練習放在了一個txt文件中,現(xiàn)在把練習代碼放到這里,有不足之處希望大家能給出指導意見及相互交流、提升。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容