Python3練習腳本

2019年6月5日11:57:32 發表評論 5,329 ℃

if  else

#!/usr/bin/python36
info={'A':'a.com','B':'b.com','C':'c.com'}
name=input('Enter name:')
if name in info:
    print(info[name])
else:
    print('NOt HAVE')

for循環

#!/usr/bin/python36
for i in range(1,20):
    print('\033[31mthe number is %s \033[0m' %i)
else:
    print('End!')

九九乘法表

#!/usr/bin/python36
for m in range(1,10):
    for n in range(1,m+1):
        print('\033[1;33m%s*%s=\033[0m\033[36m%s\033[0m\t'%(n,m,m*n),end='')
    print()

while循環

import sys
while True:
    response = input('Type exit to exit.')
    if response == 'exit':
        sys.exit()
    print('You typed ' + response + '.')

list列表

import random
messages = ['It is certain',
'It is decidedly so',
'Yes definitely',
'Reply hazy try again',
'Ask again later',
'Concentrate and ask again'
,'My reply is no',
'Outlook not so good',
'Very doubtful']
print(messages[random.randint(0, len(messages) - 1)])

1、編寫一個名為 collatz()的函數,它有一個名為 number 的參數。如果參數是偶數,那么 collatz()就打印出 number // 2,并返回該值。如果 number 是奇數,collatz()就打印并返回 3 * number + 1;然后編寫一個程序,讓用戶輸入一個整數,并不斷對這個數調用 collatz(),直到函數返回值1(考拉茲猜想)

#!/usr/bin/python36
import sys
def Collatz(Num):
    while True:
        if Num % 2 == 0:
            Num = Num//2
            print(Num)
        elif Num == 1:
            break
        else:
            Num = Num*3+1
            print(Num)
while True:
    try:
        Number = int(input('Enter int number:'))
        break
    except ValueError:
        print("Please Enter int number")

Collatz(Number)

2、編寫一個函數,它以一個列表值作為參數,返回一個字符串。該字符串包含所有表項,表項之間以逗號和空格分隔,并在最后一個表項之前插入 and。例如,將 spam 列表傳遞給函數,將返回'apples, bananas, tofu, and cats'。但你的函數應該能夠處理傳遞給它的任何列表。

#!/usr/bin/python36
spam = ['apples', 'bananas', 'tofu', 'cats']
def ListPrint(spamlist):
    for i in range(0,len(spamlist)):
        if (len(spamlist)-1) == i:
            print(spamlist[i])
        elif (len(spamlist)-2) == i:
            print(spamlist[i],end=', and ')
        else:
            print(spamlist[i],end=',')
        
ListPrint(spam)

3、假定有一個列表的列表,內層列表的每個值都是包含一個字符的字符串,像這樣:

grid = [['.', '.', '.', '.', '.', '.'],

['.', 'O', 'O', '.', '.', '.'],

['O', 'O', 'O', 'O', '.', '.'],

['O', 'O', 'O', 'O', 'O', '.'],

['.', 'O', 'O', 'O', 'O', 'O'],

['O', 'O', 'O', 'O', 'O', '.'],

['O', 'O', 'O', 'O', '.', '.'],

['.', 'O', 'O', '.', '.', '.'],

['.', '.', '.', '.', '.', '.']]

你可以認為 grid[x][y]是一幅“圖”在 x、y 坐標處的字符,該圖由文本字符組成。原點(0, 0)在左上角,向右 x 坐標增加,向下 y 坐標增加。

復制前面的網格值,編寫代碼用它打印出圖像。

..OO.OO..

.OOOOOOO.

.OOOOOOO.

..OOOOO..

...OOO...

....O....

#!/usr/bin/python3
grid = [
['.', '.', '.', '.', '.', '.'],
['.', 'O', 'O', '.', '.', '.'],
['O', 'O', 'O', 'O', '.', '.'],
['O', 'O', 'O', 'O', 'O', '.'],
['.', 'O', 'O', 'O', 'O', 'O'],
['O', 'O', 'O', 'O', 'O', '.'],
['O', 'O', 'O', 'O', '.', '.'],
['.', 'O', 'O', '.', '.', '.'],
['.', '.', '.', '.', '.', '.']]

for m in range(len(grid[0])):
    for n in range(len(grid)):
        print(grid[n][m],end=' ')
    print()

4、井字棋盤

#!/usr/bin/python36
theBoard = {
'top-L': ' ', 'top-M': ' ', 'top-R': ' ',
'mid-L': ' ', 'mid-M': ' ', 'mid-R': ' ',
'low-L': ' ', 'low-M': ' ', 'low-R': ' '}
def PrintBoard(board):
    print(board['top-L'] + '|' + board['top-M'] + '|' + board['top-R'])
    print('-+-+-')
    print(board['mid-L'] + '|' + board['mid-M'] + '|' + board['mid-R'])
    print('-+-+-')
    print(board['low-L'] + '|' + board['low-M'] + '|' + board['low-R'])

turn = 'X'
for i in range(9):
    PrintBoard(theBoard)
    move = input('請輸入' + turn + '填入的位置?')
    theBoard[move] = turn
    if turn == 'X':
        turn = 'O'
    else:
        turn = 'X'

PrintBoard(theBoard)

5、統計所有食物分類的數量

#!/usr/bin/python36
All = {'Alice': {'apples': 5, 'pretzels': 12},
'Bob': {'ham sandwiches': 3, 'apples': 2},
'Carol': {'cups': 3, 'apple pies': 1}}
def List(Food):
    foodList=[]
    for m in Food.values():
        for n in m.keys():
            foodList.append(n)
    foodList = (set(foodList))
    return foodList

def Total(total):
    foodList = List(All)
    for h in foodList:
        Num = 0
        for k in total.values():
            Num +=  k.get(h,0)
        print('Food: '+ str(h),'=' + str(Num))
Total(All)

6.1你在創建一個好玩的視頻游戲。用于對玩家物品清單建模的數據結構是一個字典。其中鍵是字符串,描述清單中的物品,值是一個整型值,說明玩家有多少該物品。例如,字典值{'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}意味著玩家有 1 條繩索、6 個火把、42 枚金幣等。

寫一個名為displayInventory()的函數,它接受任何可能的物品清單,并顯示如下:

94 Python 編程快速上手——讓繁瑣工作自動化

Inventory:

12 arrow

42 gold coin

1 rope

6 torch

1 dagger

Total number of items: 62

#!/usr/bin/python36
stuff = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}
def Game(inv):
    total =0
    for m,n in inv.items():
        total += n
        print(m,n)
    print('total number of items:' + str(total))
Game(stuff)

6.2假設征服一條龍的戰利品表示為這樣的字符串列表:dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']寫一個名為 addToInventory(inventory, addedItems)的函數,其中 inventory 參數是一個字典,表示玩家的物品清單(像前面項目一樣),addedItems 參數是一個列表,

就像 dragonLoot。addToInventory()函數應該返回一個字典,表示更新過的物品清單。

#!/usr/bin/python36
def Game(inv):
    total =0
    for m,n in inv.items():
        total += n
        print(m,n)
    print('total number of items:' + str(total))

def Tol(H,J):
    for i in J:
        H.setdefault(i,0)
        H[i] += 1
    return H

inv = {'gold coin': 42, 'rope': 1}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
Dist=(Tol(inv,dragonLoot))
Game(Dist)

7、口令保管箱,運行腳本帶上用戶參數,把用戶名對應的密碼,復制到剪切板

#!python
# pw.py - An insecure password locker program.
PASSWORDS = {'email': 'F7minlBDDuvMJuxESSKHFhTxFtjVB6',
'blog': 'VmALvQyKAxiVH5G8v01if1MLZF3sdt',
'luggage': '12345'}

import sys,pyperclip
if len(sys.argv) < 2:
    print('Usage: python pw.py [account] - copy account password')
    sys.exit()
account = sys.argv[1]

if account in PASSWORDS:
    pyperclip.copy(PASSWORDS[account])
    print('password for' + account +'copied to clipboard.')
else:
    print('There is no account named:' +account)

8、在wiki標記中添加無須列表,1.從剪貼板粘貼文本;2.對它做一些處理;3.將新的文本復制到剪貼板。復制文件,在每行文本前加上*

Lists of animals

Lists of aquarium life

Lists of biologists by author abbreviation

Lists of cultivars

#!/python
import pyperclip
text = pyperclip.paste().split('\n')
lines= []
for i in text:
    lines.append('* ' + i)

text = '\n'.join(lines)
pyperclip.copy(text)

9、編寫一個名為 printTable()的函數,它接受字符串的列表的列表,將它顯示在組織良好的表格中,每列右對齊。假定所有內層列表都包含同樣數目的字符串。例如,該值可能看起來像這樣:

tableData = [['apples', 'oranges', 'cherries', 'banana'],

['Alice', 'Bob', 'Carol', 'David'],

['dogs', 'cats', 'moose', 'goose']]

#!/usr/bin/python36
tableData = [['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose']]

def width(List):
    Widths=[]
    for m in range(len(List)):
        for n in List[m]:
            Widths.append(len(n))
    Widths.sort(reverse=True)
    return Widths[0]

def printTable(List):
    for m in range(len(List[0])):
        for n in range(len(List)):
            print(List[n][m].rjust(width(tableData)),end=' ')
        print()
printTable(tableData)

10、假設你有一個無聊的任務,要在一篇長的網頁或文章中,找出所有電話號碼和郵件地址。如果手動翻頁,可能需要查找很長時間。如果有一個程序,可以在剪貼板的文本中查找電話號碼和 E-mail 地址,那你就只要按一下 Ctrl-A 選擇所有文本,按下 Ctrl-C 將它復制到剪貼板,然后運行你的程序。它會用找到的電話號碼和 E-mail地址,替換掉剪貼板中的文本。

#!python
import pyperclip,re
telRe = re.compile(r'(\d{3})?([\.\s-])?(\d{7,8})')
mailRe = re.compile(r'[a-zA-Z0-9_-]+@[\w-]+\.[a-zA-Z]+')
List=[]
text = str(pyperclip.paste())
for groups in telRe.findall(text):
    phoneNu = ''.join([groups[0],groups[2]])
    List.append(phoneNu)

for groups in mailRe.findall(text):
    List.append(groups)

if len(List)>0:
    text='\n'.join(List)
    pyperclip.copy(text)
    print('Matching results')
    print(text)
else:
    print('no mail and phone')

11、寫一個函數,它使用正則表達式,確保傳入的口令字符串是強口令。強口令的定義是:長度不少于 8 個字符,同時包含大寫和小寫字符,至少有一位數字。你可能需要用多個正則表達式來測試該字符串,以保證它的強度。

#!/usr/bin/pyton36
import re
passWord=input('please enter your password:')
def Pwd(pwd):
    if len(passWord) > 8:
        pass1 = re.compile(r'[a-z]+')
        pass2 = re.compile(r'[A-Z]+')
        pass3 = re.compile(r'[0-9]+')
        if len(pass1.findall(pwd)) > 0 and len(pass2.findall(pwd)) > 0 and len(pass3.findall(pwd)) > 0 :
            print('password is right')
        else:
            print('password Must contain uppercase and lowercase letters and Numbers!')
    else:
        print('password must > 8')
Pwd(passWord)

12、寫一個函數,它接受一個字符串,做的事情和 strip()字符串方法一樣。如果只傳入了要去除的字符串,沒有其他參數,那么就從該字符串首尾去除空白字符。否則,函數第二個參數指定的字符將從該字符串中去除。

#!/usr/bin/python
import re
def Strip(rep,text):
    if len(rep) == 0:
        st = re.compile(r'^\s*')
        st = st.sub(rep,text)
        st1 = re.compile(r'\s*$')
        st1 = st1.sub(rep,st)
        print(st1)
    else:
        st = re.compile(rep)
        st = st.sub('',text)
        print(st)
Str = '   My name is Tom. Tom is twenty years old. Tom likes riding a bike!   '        
Strip('om',Str)
Strip('',Str)

13、生成隨機的測驗試卷文件

假如你是一位地理老師,班上有 35 名學生,你希望進行美國各州首府的一個小測驗。不妙的是,班里有幾個壞蛋,你無法確信學生不會作弊。你希望隨機調整問題的次序,這樣每份試卷都是獨一無二的,這讓任何人都不能從其他人那里抄襲答案。當然,手工完成這件事又費時又無聊。好在,你懂一些 Python。

下面是程序所做的事:

? 創建 35 份不同的測驗試卷。

? 為每份試卷創建 50 個多重選擇題,次序隨機。

? 為每個問題提供一個正確答案和 3 個隨機的錯誤答案,次序隨機。

? 將測驗試卷寫到 35 個文本文件中。

? 將答案寫到 35 個文本文件中。

這意味著代碼需要做下面的事:

? 將州和它們的首府保存在一個字典中。

? 針對測驗文本文件和答案文本文件,調用 open()、write()和 close()。

? 利用 random.shuffle()隨機調整問題和多重選項的次序。

#!/usr/bin/python36
#coding=utf-8
import random,os
capitals = {'Alabama': 'Montgomery', 'Alaska': 'Juneau', 'Arizona': 'Phoenix',
'Arkansas': 'Little Rock', 'California': 'Sacramento', 'Colorado': 'Denver',
'Connecticut': 'Hartford', 'Delaware': 'Dover', 'Florida': 'Tallahassee',
'Georgia': 'Atlanta', 'Hawaii': 'Honolulu', 'Idaho': 'Boise', 'Illinois':
'Springfield', 'Indiana': 'Indianapolis', 'Iowa': 'Des Moines', 'Kansas':
'Topeka', 'Kentucky': 'Frankfort', 'Louisiana': 'Baton Rouge', 'Maine':
'Augusta', 'Maryland': 'Annapolis', 'Massachusetts': 'Boston', 'Michigan':
'Lansing', 'Minnesota': 'Saint Paul', 'Mississippi': 'Jackson', 'Missouri':
'Jefferson City', 'Montana': 'Helena', 'Nebraska': 'Lincoln', 'Nevada':
'Carson City', 'New Hampshire': 'Concord', 'New Jersey': 'Trenton', 'NewMexico': 
'Santa Fe', 'New York': 'Albany', 'North Carolina': 'Raleigh',
'North Dakota': 'Bismarck', 'Ohio': 'Columbus', 'Oklahoma': 'Oklahoma City',
'Oregon': 'Salem', 'Pennsylvania': 'Harrisburg', 'Rhode Island': 'Providence',
'South Carolina': 'Columbia', 'South Dakota': 'Pierre', 'Tennessee':
'Nashville', 'Texas': 'Austin', 'Utah': 'Salt Lake City', 'Vermont':
'Montpelier', 'Virginia': 'Richmond', 'Washington': 'Olympia', 'WestVirginia': 
'Charleston', 'Wisconsin': 'Madison', 'Wyoming': 'Cheyenne'}

#創建臨時文件夾,保存試卷
try:
    os.makedirs(os.path.join('tmp','paper'))
except FileExistsError:
    print('',end='')
os.chdir(os.path.join('tmp','paper'))

#循環得到35份不同的試卷
for juanNum in range(35):
    juFile = open('paper%s.txt' % (juanNum + 1),'w')
    anFile = open ('paper%s_answers.txt' % (juanNum + 1),'w')
    
    #為每份試卷添加title
    juFile.write('姓名:\n\n班級:\n\n日期:\n\n得分:\n\n')
    juFile.write((' ' * 20) + '測驗試卷%s' % (juanNum + 1))
    juFile.write('\n\n') 
    
    #獲取州的列表,并隨機排序
    tiList = list(capitals.keys())
    random.shuffle(tiList)
    for tiNum in range(50):
        #州對應的州府
        daAn = capitals[tiList[tiNum]]
        #獲取所有的州府
        errorList = list(capitals.values())
        #刪除此次循環州對應的州府
        errorList.remove(daAn)
        #再剩下的49個州府中,隨機取3個州府
        errorDaan = random.sample(errorList,3)
        #創建選項列表,并隨機排序
        daanList = [daAn] + errorDaan
        random.shuffle(daanList)
        #打印題目
        juFile.write(str(tiNum + 1 ) + '.' + tiList[tiNum] + '的州府城市是什么?\n')
        #循環打印選項
        for daNum in range(4):
            juFile.write('ABCD'[daNum] + '.' + daanList[daNum]+ '\n')
        
        anFile.write(str(tiNum +1) + '.' +'ABCD'[daanList.index(daAn)] + '\n')
        juFile.write('\n')

    juFile.close()
    anFile.close()

14、編寫一個 Python 程序,追蹤幾段文本。這個“多重剪貼板”將被命名為mcb.pyw(因為“mcb”比輸入“multiclipboard”更簡單)。.pyw 擴展名意味著 Python運行該程序時,不會顯示終端窗口,該程序將利用一個關鍵字保存每段剪貼板文本。例如,當運行 py mcb.pyw save spam,剪貼板中當前的內容就用關鍵字 spam 保存;運行 py mcb.pyw delete spam,將從 shelf 中刪除一個關鍵字;通過運行 py mcb.pyw spam,這段文本稍后將重新加載到剪貼板中。如果用戶忘記了都有哪些關鍵字,他們可以運行 py mcb.pyw list,將所有關鍵字的列表復制到剪貼板中。

下面是程序要做的事:

? 針對要檢查的關鍵字,提供命令行參數。

? 如果參數是 save,那么將剪貼板的內容保存到關鍵字。

? 如果參數是 list,就將所有的關鍵字拷貝到剪貼板。

? 否則,就將關鍵詞對應的文本拷貝到剪貼板。

這意味著代碼需要做下列事情:

? 從 sys.argv 讀取命令行參數。

? 讀寫剪貼板。

? 保存并加載 shelf 文件。

#!python3
#mcb.pyw - Saves and loads pieces of text to the clipboard.
#Usage:
#py.exe mcb.pyw save <keyword> - Saves clipboard to keyword.
#py.exe mcb.pyw delete <keyword> - delete clipboard to keyword.
#py.exe mcb.pyw <keyword> - Loads keyword to clipboard.
#py.exe mcb.pyw list - Loads all keywords to clipboard.
import sys,pyperclip,shelve
mcbShelf = shelve.open('mcb')
if len(sys.argv) == 3 and sys.argv[1].lower() == 'save':
    mcbShelf[sys.argv[2]] = pyperclip.paste()
elif len(sys.argv) == 3 and sys.argv[1].lower() == 'delete':
    if sys.argv[2] in mcbShelf:
        del mcbShelf[sys.argv[2]]
elif len(sys.argv) == 2:
    if sys.argv[1].lower() == 'list':
        pyperclip.copy(str(list(mcbShelf.keys())))
    elif sys.argv[1] in mcbShelf:
        pyperclip.copy(mcbShelf[sys.argv[1]])
mcbShelf.close()

15、創建一個瘋狂填詞(Mad Libs)程序,它將讀入文本文件,并讓用戶在該文本文件中出現 ADJECTIVE、NOUN、ADVERB 或 VERB 等單詞的地方,加上他們自己的文本。例如,一個文本文件可能看起來像這樣:The ADJECTIVE panda walked to the NOUN and then VERB. A nearby NOUN was unaffected by these events.

程序將找到這些出現的單詞,并提示用戶取代它們。

#!/usr/bin/python36
import os,re 
textFile = open('test.txt')
text = textFile.read()

subList = ['ADJECTIVE','NOUN','ADVERB','VERB']
for m in subList:
    testRe = re.compile(m,re.I)
    while True:
        if len(list(testRe.findall(text))) :
            newWord = input('Enter an ' + m.lower() + ': ')
            text = testRe.sub(newWord,text,1)
        else:
            break
print(text)
newFile = open('new_test.txt','w')
newFile.write(text + '\n')
textFile.close()
newFile.close()

16、編寫一個程序,打開文件夾中所有的.txt 文件,查找匹配用戶提供的正則表達式的所有行。結果應該打印到屏幕上。

#!/usr/bin/python36
import os,re
txtList=os.listdir('/tmp/test')
for m in txtList:
    if os.path.splitext(m)[1] == '.txt':
        txtFile = os.path.join('/tmp/test',m)
        print(txtFile)
        txt = open(txtFile)
        txts = txt.readlines()
        for n in txts:
            reTxt = re.compile(r'\d+')
            if len(reTxt.findall(n)) > 0:
                print(n)
        txt.close()

17、將帶有美國風格日期的文件改名為歐洲風格日期假定你的老板用電子郵件發給你上千個文件,文件名包含美國風格的日期(MM-DD-YYYY),需要將它們改名為歐洲風格的日期(DD-MM-YYYY)。手工完

成這個無聊的任務可能需要幾天時間!讓我們寫一個程序來完成它。

下面是程序要做的事:

? 檢查當前工作目錄的所有文件名,尋找美國風格的日期。

? 如果找到,將該文件改名,交換月份和日期的位置,使之成為歐洲風格。

這意味著代碼需要做下面的事情:

? 創建一個正則表達式,可以識別美國風格日期的文本模式。

? 調用 os.listdir(),找出工作目錄中的所有文件。

? 循環遍歷每個文件名,利用該正則表達式檢查它是否包含日期。

? 如果它包含日期,用 shutil.move()對該文件改名。

對于這個項目,打開一個新的文件編輯器窗口,將代碼保存為 renameDates.py。

#!/usr/bin/python36
#coding=utf-8
import os,re,shutil
dateRe=re.compile(r'^(.*?)((0|1)?\d)-((0|1|2|3)?\d)-((19|20)\d\d)(.*?)$')
for m in os.listdir('/tmp/text'):
    fileName = dateRe.search(m)
    if fileName == None:
        continue
    else:
        qianZui = fileName.group(1)
        yue = fileName.group(2)
        tian = fileName.group(4)
        nian = fileName.group(6)
        houZui = fileName.group(8)
    newName = qianZui + tian + '-' + yue + '-' + nian + houZui
    os.chdir('/tmp/text')
    print('原名:"%s" 現名:"%s"'%(m,newName))
    shutil.move(m,newName)

18、假定你正在做一個項目,它的文件保存在/tmp/text 文件夾中。你擔心工作會丟失,所以希望為整個文件夾創建一個ZIP 文件,作為“快照”。你希望保存不同的版本,希望 ZIP 文件的文件名每次創建時都有所變化。

#!/usr/bin/pyton36
import zipfile,os,datetime

def nowTime():
    timeNow = datetime.datetime.now()
    timeStr = timeNow.strftime('%Y%m%d%H%M%S')
    return timeStr

def zipFile(files):
    baseName = os.path.basename(files)
    dirName = os.path.dirname(files)
    fileZip = zipfile.ZipFile(nowTime()+'.zip','w',zipfile.ZIP_DEFLATED)

    os.chdir(dirName)
    fileList = os.walk(baseName)
    for f,s,n in fileList:
        for name in n:
            print(os.path.join(f,name))
            fileZip.write(os.path.join(f,name))
    fileZip.close()

zipFile('/tmp/text')

19、編寫一個程序,在一個文件夾中,找到所有帶指定前綴的文件,諸如 spam001.txt, spam002.txt 等,并定位缺失的編號(例如存在 spam001.txt 和 spam003.txt,但不存在 spam002.txt)。讓該程序對所有后面的文件改名,消除缺失的編號。

#!/usr/bin/python36
import os,shutil
os.chdir('/tmp/test2')
fileName = os.listdir('.')
for i in range(len(fileName)):
    name = 'spam00' + str(i + 1) + '.txt'
    if os.path.exists(name):
        continue
    else:
        shutil.move(fileName[i],name)

20、每次我在 Google 上搜索一個主題時,都不會一次只看一個搜索結果。通過鼠標中鍵點擊搜索結果鏈接,或在點擊時按住 CTRL 鍵,我會在一些新的選項卡中打開前幾個鏈接,稍后再來查看。我經常搜索 Google,所以這個工作流程(開瀏覽器,查找一個主題,依次用中鍵點擊幾個鏈接)變得很乏味。如果我只要在命令行中輸入查找主題,就能讓計算機自動打開瀏覽器,并在新的選項卡中顯示前面幾項查詢結果,那就太好了。讓我們寫一個腳本來完成這件事。

#!python
#conding=utf-8
import requests, sys, webbrowser, bs4

res = requests.get('http://www.baidu.com/s?wd=' + ' '.join(sys.argv[1:]))
res.raise_for_status()
soup = bs4.BeautifulSoup(res.text,'html.parser')
linkElems = soup.select('div .f13 a[style="text-decoration:none;"]')
for i in range(min(5,len(linkElems))):
    webbrowser.open(linkElems[i].get('href'))

21、博客和其他經常更新的網站通常有一個首頁,其中有最新的帖子,以及一個“前一篇”按鈕,將你帶到以前的帖子。然后那個帖子也有一個“前一篇”按鈕,以此類推。這創建了一條線索,從最近的頁面,直到該網站的第一個帖子。如果你希望拷貝該網站的內容,在離線的時候閱讀,可以手工導航至每個頁面并保存。但這是很無聊的工作,所以讓我們寫一個程序來做這件事。

XKCD 是一個流行的極客漫畫網站,它符合這個結構。首頁http://xkcd.com/有一個“Prev”按鈕,讓用戶導航到前面的漫畫。手工下載每張漫畫要花較長的時間,但你可以寫一個腳本,在幾分鐘內完成這件事。

#!python
import bs4, requests, os
url = 'http://xkcd.com'
os.makedirs('xkcd',exist_ok=True)
while not url.endswith('#'):
    print('Downloading page %s...'% url)
    res = requests.get(url)
    res.raise_for_status()

    soup = bs4.BeautifulSoup(res.text,'html.parser')
    img = soup.select('#comic img')
    if img == []:
        print('could not find comic image.')
    else:
        imgUrl = 'http:' + img[0].get('src')
        print('Download image %s...'% imgUrl)
        res = requests.get(imgUrl)
        res.raise_for_status()

        imgFile = open(os.path.join('xkcd',os.path.basename(imgUrl)), 'wb')
        for chunk in res.iter_content(100000):
            imgFile.write(chunk)
        imgFile.close()
    link = soup.select('a[rel="prev"]')
    url = 'http://xkcd.com' + link[0].get('href')

擴展:使用多線程下載圖片

#!python
import bs4, requests, os,threading
os.makedirs('xkcd',exist_ok=True)

#定義下載函數,并傳遞開始和結束URL數字
def downloadImg(startNum,endNum):
    for urlNum in range(startNum,endNum):
        url = 'http://xkcd.com/' + str(urlNum)
        print('Downloading page %s...'%(url))
        res = requests.get(url)
        res.raise_for_status()

        soup = bs4.BeautifulSoup(res.text,'html.parser')
        img = soup.select('#comic img')
        
        #判斷圖片是否存在
        if img == []:
            print('could not find comic image.')
        else:
            imgUrl = 'http:' + img[0].get('src')
            print('Download image %s...'%(imgUrl))
            res = requests.get(imgUrl)
            res.raise_for_status()

            #循環下載圖片保存到本地
            imgFile = open(os.path.join('xkcd',os.path.basename(imgUrl)), 'wb')
            for chunk in res.iter_content(100000):
                imgFile.write(chunk)
            imgFile.close()
            
#獲取總共頁面
res = requests.get('http://xkcd.com')
res.raise_for_status()
soup = bs4.BeautifulSoup(res.text,'html.parser')
totalNum = int(soup.select('a[rel="prev"]')[0].get('href').strip('/'))

#創建并啟動線程
downloadThreads = []
for i in range(0,totalNum,100):
    if  i ==(totalNum//100) * 100:
        downloadThread = threading.Thread(target=downloadImg,args=(i,totalNum + 1 ))
    else:
        downloadThread = threading.Thread(target=downloadImg,args=(i,i + 99 ))
    downloadThreads.append(downloadThread)
    downloadThread.start()

#等待所有線程結束完成下載
for th in downloadThreads:
    th.join()
print('Download Done!')

22、編寫一個程序,通過命令行接受電子郵件地址和文本字符串。然后利用 selenium登錄到你的郵件賬號,將該字符串作為郵件,發送到提供的地址。

#!python3
import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

chrome = webdriver.Chrome()
chrome.get('http://w.mail.qq.com/cgi-bin/loginpage?f=xhtml')

#獲取元素填寫賬號登錄
nameElem = chrome.find_element_by_id('u')
nameElem.send_keys('***')
passWord = chrome.find_element_by_id('p')
passWord.send_keys('***')
passWord.send_keys(Keys.ENTER)

time.sleep(2)

#打開發件箱
linkElem = chrome.find_element_by_class_name('qm_btnIcon')
linkElem.click()

#填寫發件郵箱
mailUser = chrome.find_element_by_id('showto')
mailUser.send_keys('***@qq.com')
#填寫主題
mailTheme = chrome.find_element_by_id('subject')
mailTheme.send_keys('這是一封來自python3的郵件')
#填寫內容
mailContent = chrome.find_element_by_id('content')
mailContent.send_keys('Hollow Word!\n Hollow Python!')
#發送
mailSend = chrome.find_element_by_class_name("qm_btn_Blue")
mailSend.click()

23、2048 是一個簡單的游戲,通過箭頭向上、下、左、右移動滑塊,讓滑塊合并。實際上,你可以通過一遍一遍的重復“上、右、下、左”模式,獲得相當高的分數。編寫一個程序,打開 https://play2048.co/上的游戲,不斷發送上、右、下、左按鍵,自動玩游戲。

#!pyton3
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

game = webdriver.Chrome()
game.get('http://play2048.co/')

elem = game.find_element_by_tag_name('html')
while True:
    elem.send_keys(Keys.UP)
    elem.send_keys(Keys.RIGHT)
    elem.send_keys(Keys.DOWN)
    elem.send_keys(Keys.LEFT)

24、編寫一個程序,對給定的網頁 URL,下載該頁面所有鏈接的頁面。程序應該標記出所有具有 404“Not Found”狀態碼的頁面,將它們作為壞鏈接輸出。

#!python3
import bs4,requests

res = requests.get('http://www.9pinw.com')
res.raise_for_status()
soup = bs4.BeautifulSoup(res.text,'html.parser')
elems = soup.select('a')

#循環讀取鏈接
for i in range(len(elems)):
    url = elems[i].get('href')
    if url.startswith('http:'):
        try:
            newRe = requests.get(url)
            if newRe.status_code == 404:
                print(url + ' ' + str(newRe.status_code))
        except requests.exceptions.SSLError:
            print('https Error')
    else:
        newUrl = ''.join(['http://www.9pinw.com/',url.lstrip('../')])
        newRe = requests.get(newUrl)
        if newRe.status_code == 404:
            print(newUrl + ' ' + str(newRe.status_code))

25、編寫一個腳本獲取今后幾天的天氣預報,當執行tianqi.py city 就會把當前city天氣以純文本打印出來。

#!python3
#conding=utf-8
import requests,json,sys
if len(sys.argv) < 2:
    print('Usage:tianqi.py location')
    sys.exit()

#獲取參數城市    
location =' '.join(sys.argv[1:])
apiUrl = 'http://wthrcdn.etouch.cn/weather_mini?city=%s' %(location)
res = requests.get(apiUrl)
res.raise_for_status()
#獲取天氣json數據
jsonDate = json.loads(res.text)
tianQi = ((jsonDate['data'])['forecast'])
print(location,'未來%s天天氣情況:'%(len(tianQi)))
#循環輸出未來幾天天氣情況
for i in range(len(tianQi)):
    print(tianQi[i]['date'] + ' '+ tianQi[i]['high'] + ' ' + tianQi[i]['low'] + ' ' + tianQi[i]['type'])

26、假設要記錄在沒有自動化的枯燥任務上花了多少時間。你沒有物理秒表,要為筆記本或智能手機找到一個免費的秒表應用,沒有廣告,且不會將你的瀏覽歷史發送給市場營銷人員,又出乎意料地困難(在你同意的許可協議中,它說它可以這樣做。你確實閱讀了許可協議,不是嗎?)。你可以自己用 Python 寫一個簡單的秒表程序。

#!/usr/bin/python36
#conding=utf8
import time
print('請按回車鍵開始,再次按下回車鍵記錄第二次計時,按下Ctrl+C結束')
input()
print('start')
startTime = time.time()
lastTime = startTime
lapNum = 1
try:
    while True:
        input()
        lapTime = round(time.time() - lastTime,2)
        totalTime = round(time.time() - startTime,2)
        print('第%s圈,用時:%s,總時:%s'%(lapNum,lapTime,totalTime))
        #strLap = '第%s圈'%lapNum
        #strlapTime = '用時:%s'%lapTime
        #strtotalTime = '總時:%s'%totalTime
        #print(strLap.ljust(8) + strlapTime.ljust(12) + strtotalTime.ljust(8))
        lapNum += 1
        lastTime = time.time()
except KeyboardInterrupt:
    print('Done')

27、簡單的倒計時程序,就像很難找到一個簡單的秒表應用程序一樣,也很難找到一個簡單的倒計時程序。讓我們來寫一個倒計時程序,在倒計時結束時報警。

#!python
import time,subprocess
timeLeft = 5
while timeLeft > 0:
    print(timeLeft,end=' ')
    time.sleep(1)
    timeLeft -= 1
    
subprocess.Popen(['start','windows.wav'],shell=True)

28、假設你有一項無聊的工作,要調整數千張圖片的大小,并在每張圖片的角上增加一個小徽標水印。使用基本的圖形程序,如 Paintbrush 或 Paint,完成這項工作需要很長時間。像 Photoshop 這樣神奇的應用程序可以批量處理,但這個軟件要花幾百美元。讓我們寫一個腳本來完成工作。

的來說,程序應該完成下面的事:

? 載入徽標圖像。

? 循環遍歷工作目標中的所有.png 和.jpg 文件。

? 檢查圖片是否寬于或高于 300 像素。

? 如果是,將寬度或高度中較大的一個減小為300 像素,并按比例縮小的另一維度。

? 在角上粘貼徽標圖像。

? 將改變的圖像存入另一個文件夾。

#! python3

import os
from PIL import Image

SQUARE_FIT_SIZE = 300
LOGO_FILENAME = 'catlogo.png'

logoIm = Image.open(LOGO_FILENAME)
logoWidth, logoHeight = logoIm.size

os.makedirs('withLogo', exist_ok=True)
# Loop over all files in the working directory.
for filename in os.listdir('.'):
    if not (filename.endswith('.png') or filename.endswith('.jpg')) \
       or filename == LOGO_FILENAME:
        continue # skip non-image files and the logo file itself

    im = Image.open(filename)
    width, height = im.size

    # Check if image needs to be resized.
    if width > SQUARE_FIT_SIZE and height > SQUARE_FIT_SIZE:
        # Calculate the new width and height to resize to.
        if width > height:
            height = int((SQUARE_FIT_SIZE / width) * height)
            width = SQUARE_FIT_SIZE
        else:
            width = int((SQUARE_FIT_SIZE / height) * width)
            height = SQUARE_FIT_SIZE

        # Resize the image.
        print('Resizing %s...' % (filename))
        im = im.resize((width, height))

    # Add logo.
    print('Adding logo to %s...' % (filename))
    im.paste(logoIm, (width - logoWidth, height - logoHeight), logoIm)

    # Save changes.
    im.save(os.path.join('withLogo', filename))

29、能夠確定鼠標的位置,對于建立 GUI 自動化腳本是很重要的。但光看屏幕,幾乎不能弄清楚像素的準確坐標。如果有一個程序在移動鼠標時隨時顯示 x y 坐標,就會很方便。

總的來說,你希望該程序做到:

獲得鼠標當前的 xy 坐標。

當鼠標在屏幕上移動時,更新這些坐標。

這意味著代碼需要做到下列事情:

調用函數取得當前坐標。

在屏幕上打印回退制服。刪除以前打印的坐標。

處理異常。讓用戶能按鍵退出

#!python
#conding=utf-8
import pyautogui
print('請按Ctrl+C鍵退出')
fist = pyautogui.position()
try:
    while True:
        two = pyautogui.position()
        if fist != two:
            x,y = two
            positionStr = 'X:' + str(x).rjust(4) + ' Y:' + str(y).rjust(4)
            print(positionStr,end='')
            print('\b' * len(positionStr), end='', flush=True)
            fist = two
except KeyboardInterrupt:
    print('退出!')

【騰訊云】云服務器、云數據庫、COS、CDN、短信等云產品特惠熱賣中

發表評論

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: