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循環(huán)
#!/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循環(huán)
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、編寫(xiě)一個(gè)名為 collatz()的函數(shù),它有一個(gè)名為 number 的參數(shù)。如果參數(shù)是偶數(shù),那么 collatz()就打印出 number // 2,并返回該值。如果 number 是奇數(shù),collatz()就打印并返回 3 * number + 1;然后編寫(xiě)一個(gè)程序,讓用戶輸入一個(gè)整數(shù),并不斷對(duì)這個(gè)數(shù)調(diào)用 collatz(),直到函數(shù)返回值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、編寫(xiě)一個(gè)函數(shù),它以一個(gè)列表值作為參數(shù),返回一個(gè)字符串。該字符串包含所有表項(xiàng),表項(xiàng)之間以逗號(hào)和空格分隔,并在最后一個(gè)表項(xiàng)之前插入 and。例如,將 spam 列表傳遞給函數(shù),將返回'apples, bananas, tofu, and cats'。但你的函數(shù)應(yīng)該能夠處理傳遞給它的任何列表。
#!/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、假定有一個(gè)列表的列表,內(nèi)層列表的每個(gè)值都是包含一個(gè)字符的字符串,像這樣:
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', '.', '.', '.'],
['.', '.', '.', '.', '.', '.']]
你可以認(rèn)為 grid[x][y]是一幅“圖”在 x、y 坐標(biāo)處的字符,該圖由文本字符組成。原點(diǎn)(0, 0)在左上角,向右 x 坐標(biāo)增加,向下 y 坐標(biāo)增加。
復(fù)制前面的網(wǎng)格值,編寫(xiě)代碼用它打印出圖像。
..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、井字棋盤(pán)
#!/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('請(qǐng)輸入' + turn + '填入的位置?') theBoard[move] = turn if turn == 'X': turn = 'O' else: turn = 'X' PrintBoard(theBoard)
5、統(tǒng)計(jì)所有食物分類(lèi)的數(shù)量
#!/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你在創(chuàng)建一個(gè)好玩的視頻游戲。用于對(duì)玩家物品清單建模的數(shù)據(jù)結(jié)構(gòu)是一個(gè)字典。其中鍵是字符串,描述清單中的物品,值是一個(gè)整型值,說(shuō)明玩家有多少該物品。例如,字典值{'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}意味著玩家有 1 條繩索、6 個(gè)火把、42 枚金幣等。
寫(xiě)一個(gè)名為displayInventory()的函數(shù),它接受任何可能的物品清單,并顯示如下:
94 Python 編程快速上手——讓繁瑣工作自動(dòng)化
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假設(shè)征服一條龍的戰(zhàn)利品表示為這樣的字符串列表:dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']寫(xiě)一個(gè)名為 addToInventory(inventory, addedItems)的函數(shù),其中 inventory 參數(shù)是一個(gè)字典,表示玩家的物品清單(像前面項(xiàng)目一樣),addedItems 參數(shù)是一個(gè)列表,
就像 dragonLoot。addToInventory()函數(shù)應(yīng)該返回一個(gè)字典,表示更新過(guò)的物品清單。
#!/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、口令保管箱,運(yùn)行腳本帶上用戶參數(shù),把用戶名對(duì)應(yīng)的密碼,復(fù)制到剪切板
#!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標(biāo)記中添加無(wú)須列表,1.從剪貼板粘貼文本;2.對(duì)它做一些處理;3.將新的文本復(fù)制到剪貼板。復(fù)制文件,在每行文本前加上*
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、編寫(xiě)一個(gè)名為 printTable()的函數(shù),它接受字符串的列表的列表,將它顯示在組織良好的表格中,每列右對(duì)齊。假定所有內(nèi)層列表都包含同樣數(shù)目的字符串。例如,該值可能看起來(lái)像這樣:
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、假設(shè)你有一個(gè)無(wú)聊的任務(wù),要在一篇長(zhǎng)的網(wǎng)頁(yè)或文章中,找出所有電話號(hào)碼和郵件地址。如果手動(dòng)翻頁(yè),可能需要查找很長(zhǎng)時(shí)間。如果有一個(gè)程序,可以在剪貼板的文本中查找電話號(hào)碼和 E-mail 地址,那你就只要按一下 Ctrl-A 選擇所有文本,按下 Ctrl-C 將它復(fù)制到剪貼板,然后運(yùn)行你的程序。它會(huì)用找到的電話號(hào)碼和 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、寫(xiě)一個(gè)函數(shù),它使用正則表達(dá)式,確保傳入的口令字符串是強(qiáng)口令。強(qiáng)口令的定義是:長(zhǎng)度不少于 8 個(gè)字符,同時(shí)包含大寫(xiě)和小寫(xiě)字符,至少有一位數(shù)字。你可能需要用多個(gè)正則表達(dá)式來(lái)測(cè)試該字符串,以保證它的強(qiáng)度。
#!/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、寫(xiě)一個(gè)函數(shù),它接受一個(gè)字符串,做的事情和 strip()字符串方法一樣。如果只傳入了要去除的字符串,沒(méi)有其他參數(shù),那么就從該字符串首尾去除空白字符。否則,函數(shù)第二個(gè)參數(shù)指定的字符將從該字符串中去除。
#!/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、生成隨機(jī)的測(cè)驗(yàn)試卷文件
假如你是一位地理老師,班上有 35 名學(xué)生,你希望進(jìn)行美國(guó)各州首府的一個(gè)小測(cè)驗(yàn)。不妙的是,班里有幾個(gè)壞蛋,你無(wú)法確信學(xué)生不會(huì)作弊。你希望隨機(jī)調(diào)整問(wèn)題的次序,這樣每份試卷都是獨(dú)一無(wú)二的,這讓任何人都不能從其他人那里抄襲答案。當(dāng)然,手工完成這件事又費(fèi)時(shí)又無(wú)聊。好在,你懂一些 Python。
下面是程序所做的事:
? 創(chuàng)建 35 份不同的測(cè)驗(yàn)試卷。
? 為每份試卷創(chuàng)建 50 個(gè)多重選擇題,次序隨機(jī)。
? 為每個(gè)問(wèn)題提供一個(gè)正確答案和 3 個(gè)隨機(jī)的錯(cuò)誤答案,次序隨機(jī)。
? 將測(cè)驗(yàn)試卷寫(xiě)到 35 個(gè)文本文件中。
? 將答案寫(xiě)到 35 個(gè)文本文件中。
這意味著代碼需要做下面的事:
? 將州和它們的首府保存在一個(gè)字典中。
? 針對(duì)測(cè)驗(yàn)文本文件和答案文本文件,調(diào)用 open()、write()和 close()。
? 利用 random.shuffle()隨機(jī)調(diào)整問(wèn)題和多重選項(xiàng)的次序。
#!/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'} #創(chuàng)建臨時(shí)文件夾,保存試卷 try: os.makedirs(os.path.join('tmp','paper')) except FileExistsError: print('',end='') os.chdir(os.path.join('tmp','paper')) #循環(huán)得到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班級(jí):\n\n日期:\n\n得分:\n\n') juFile.write((' ' * 20) + '測(cè)驗(yàn)試卷%s' % (juanNum + 1)) juFile.write('\n\n') #獲取州的列表,并隨機(jī)排序 tiList = list(capitals.keys()) random.shuffle(tiList) for tiNum in range(50): #州對(duì)應(yīng)的州府 daAn = capitals[tiList[tiNum]] #獲取所有的州府 errorList = list(capitals.values()) #刪除此次循環(huán)州對(duì)應(yīng)的州府 errorList.remove(daAn) #再剩下的49個(gè)州府中,隨機(jī)取3個(gè)州府 errorDaan = random.sample(errorList,3) #創(chuàng)建選項(xiàng)列表,并隨機(jī)排序 daanList = [daAn] + errorDaan random.shuffle(daanList) #打印題目 juFile.write(str(tiNum + 1 ) + '.' + tiList[tiNum] + '的州府城市是什么?\n') #循環(huán)打印選項(xiàng) 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、編寫(xiě)一個(gè) Python 程序,追蹤幾段文本。這個(gè)“多重剪貼板”將被命名為mcb.pyw(因?yàn)椤癿cb”比輸入“multiclipboard”更簡(jiǎn)單)。.pyw 擴(kuò)展名意味著 Python運(yùn)行該程序時(shí),不會(huì)顯示終端窗口,該程序?qū)⒗靡粋€(gè)關(guān)鍵字保存每段剪貼板文本。例如,當(dāng)運(yùn)行 py mcb.pyw save spam,剪貼板中當(dāng)前的內(nèi)容就用關(guān)鍵字 spam 保存;運(yùn)行 py mcb.pyw delete spam,將從 shelf 中刪除一個(gè)關(guān)鍵字;通過(guò)運(yùn)行 py mcb.pyw spam,這段文本稍后將重新加載到剪貼板中。如果用戶忘記了都有哪些關(guān)鍵字,他們可以運(yùn)行 py mcb.pyw list,將所有關(guān)鍵字的列表復(fù)制到剪貼板中。
下面是程序要做的事:
? 針對(duì)要檢查的關(guān)鍵字,提供命令行參數(shù)。
? 如果參數(shù)是 save,那么將剪貼板的內(nèi)容保存到關(guān)鍵字。
? 如果參數(shù)是 list,就將所有的關(guān)鍵字拷貝到剪貼板。
? 否則,就將關(guān)鍵詞對(duì)應(yīng)的文本拷貝到剪貼板。
這意味著代碼需要做下列事情:
? 從 sys.argv 讀取命令行參數(shù)。
? 讀寫(xiě)剪貼板。
? 保存并加載 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、創(chuàng)建一個(gè)瘋狂填詞(Mad Libs)程序,它將讀入文本文件,并讓用戶在該文本文件中出現(xiàn) ADJECTIVE、NOUN、ADVERB 或 VERB 等單詞的地方,加上他們自己的文本。例如,一個(gè)文本文件可能看起來(lái)像這樣:The ADJECTIVE panda walked to the NOUN and then VERB. A nearby NOUN was unaffected by these events.
程序?qū)⒄业竭@些出現(xiàn)的單詞,并提示用戶取代它們。
#!/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、編寫(xiě)一個(gè)程序,打開(kāi)文件夾中所有的.txt 文件,查找匹配用戶提供的正則表達(dá)式的所有行。結(jié)果應(yīng)該打印到屏幕上。
#!/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、將帶有美國(guó)風(fēng)格日期的文件改名為歐洲風(fēng)格日期假定你的老板用電子郵件發(fā)給你上千個(gè)文件,文件名包含美國(guó)風(fēng)格的日期(MM-DD-YYYY),需要將它們改名為歐洲風(fēng)格的日期(DD-MM-YYYY)。手工完
成這個(gè)無(wú)聊的任務(wù)可能需要幾天時(shí)間!讓我們寫(xiě)一個(gè)程序來(lái)完成它。
下面是程序要做的事:
? 檢查當(dāng)前工作目錄的所有文件名,尋找美國(guó)風(fēng)格的日期。
? 如果找到,將該文件改名,交換月份和日期的位置,使之成為歐洲風(fēng)格。
這意味著代碼需要做下面的事情:
? 創(chuàng)建一個(gè)正則表達(dá)式,可以識(shí)別美國(guó)風(fēng)格日期的文本模式。
? 調(diào)用 os.listdir(),找出工作目錄中的所有文件。
? 循環(huán)遍歷每個(gè)文件名,利用該正則表達(dá)式檢查它是否包含日期。
? 如果它包含日期,用 shutil.move()對(duì)該文件改名。
對(duì)于這個(gè)項(xiàng)目,打開(kāi)一個(gè)新的文件編輯器窗口,將代碼保存為 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" 現(xiàn)名:"%s"'%(m,newName)) shutil.move(m,newName)
18、假定你正在做一個(gè)項(xiàng)目,它的文件保存在/tmp/text 文件夾中。你擔(dān)心工作會(huì)丟失,所以希望為整個(gè)文件夾創(chuàng)建一個(gè)ZIP 文件,作為“快照”。你希望保存不同的版本,希望 ZIP 文件的文件名每次創(chuàng)建時(shí)都有所變化。
#!/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、編寫(xiě)一個(gè)程序,在一個(gè)文件夾中,找到所有帶指定前綴的文件,諸如 spam001.txt, spam002.txt 等,并定位缺失的編號(hào)(例如存在 spam001.txt 和 spam003.txt,但不存在 spam002.txt)。讓該程序?qū)λ泻竺娴奈募拿笔У木幪?hào)。
#!/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 上搜索一個(gè)主題時(shí),都不會(huì)一次只看一個(gè)搜索結(jié)果。通過(guò)鼠標(biāo)中鍵點(diǎn)擊搜索結(jié)果鏈接,或在點(diǎn)擊時(shí)按住 CTRL 鍵,我會(huì)在一些新的選項(xiàng)卡中打開(kāi)前幾個(gè)鏈接,稍后再來(lái)查看。我經(jīng)常搜索 Google,所以這個(gè)工作流程(開(kāi)瀏覽器,查找一個(gè)主題,依次用中鍵點(diǎn)擊幾個(gè)鏈接)變得很乏味。如果我只要在命令行中輸入查找主題,就能讓計(jì)算機(jī)自動(dòng)打開(kāi)瀏覽器,并在新的選項(xiàng)卡中顯示前面幾項(xiàng)查詢結(jié)果,那就太好了。讓我們寫(xiě)一個(gè)腳本來(lái)完成這件事。
#!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、博客和其他經(jīng)常更新的網(wǎng)站通常有一個(gè)首頁(yè),其中有最新的帖子,以及一個(gè)“前一篇”按鈕,將你帶到以前的帖子。然后那個(gè)帖子也有一個(gè)“前一篇”按鈕,以此類(lèi)推。這創(chuàng)建了一條線索,從最近的頁(yè)面,直到該網(wǎng)站的第一個(gè)帖子。如果你希望拷貝該網(wǎng)站的內(nèi)容,在離線的時(shí)候閱讀,可以手工導(dǎo)航至每個(gè)頁(yè)面并保存。但這是很無(wú)聊的工作,所以讓我們寫(xiě)一個(gè)程序來(lái)做這件事。
XKCD 是一個(gè)流行的極客漫畫(huà)網(wǎng)站,它符合這個(gè)結(jié)構(gòu)。首頁(yè)http://xkcd.com/有一個(gè)“Prev”按鈕,讓用戶導(dǎo)航到前面的漫畫(huà)。手工下載每張漫畫(huà)要花較長(zhǎng)的時(shí)間,但你可以寫(xiě)一個(gè)腳本,在幾分鐘內(nèi)完成這件事。
#!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')
擴(kuò)展:使用多線程下載圖片
#!python import bs4, requests, os,threading os.makedirs('xkcd',exist_ok=True) #定義下載函數(shù),并傳遞開(kāi)始和結(jié)束URL數(shù)字 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() #循環(huán)下載圖片保存到本地 imgFile = open(os.path.join('xkcd',os.path.basename(imgUrl)), 'wb') for chunk in res.iter_content(100000): imgFile.write(chunk) imgFile.close() #獲取總共頁(yè)面 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('/')) #創(chuàng)建并啟動(dòng)線程 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() #等待所有線程結(jié)束完成下載 for th in downloadThreads: th.join() print('Download Done!')
22、編寫(xiě)一個(gè)程序,通過(guò)命令行接受電子郵件地址和文本字符串。然后利用 selenium登錄到你的郵件賬號(hào),將該字符串作為郵件,發(fā)送到提供的地址。
#!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') #獲取元素填寫(xiě)賬號(hào)登錄 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) #打開(kāi)發(fā)件箱 linkElem = chrome.find_element_by_class_name('qm_btnIcon') linkElem.click() #填寫(xiě)發(fā)件郵箱 mailUser = chrome.find_element_by_id('showto') mailUser.send_keys('***@qq.com') #填寫(xiě)主題 mailTheme = chrome.find_element_by_id('subject') mailTheme.send_keys('這是一封來(lái)自python3的郵件') #填寫(xiě)內(nèi)容 mailContent = chrome.find_element_by_id('content') mailContent.send_keys('Hollow Word!\n Hollow Python!') #發(fā)送 mailSend = chrome.find_element_by_class_name("qm_btn_Blue") mailSend.click()
23、2048 是一個(gè)簡(jiǎn)單的游戲,通過(guò)箭頭向上、下、左、右移動(dòng)滑塊,讓滑塊合并。實(shí)際上,你可以通過(guò)一遍一遍的重復(fù)“上、右、下、左”模式,獲得相當(dāng)高的分?jǐn)?shù)。編寫(xiě)一個(gè)程序,打開(kāi) https://play2048.co/上的游戲,不斷發(fā)送上、右、下、左按鍵,自動(dòng)玩游戲。
#!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、編寫(xiě)一個(gè)程序,對(duì)給定的網(wǎng)頁(yè) URL,下載該頁(yè)面所有鏈接的頁(yè)面。程序應(yīng)該標(biāo)記出所有具有 404“Not Found”狀態(tài)碼的頁(yè)面,將它們作為壞鏈接輸出。
#!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') #循環(huán)讀取鏈接 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、編寫(xiě)一個(gè)腳本獲取今后幾天的天氣預(yù)報(bào),當(dāng)執(zhí)行tianqi.py city 就會(huì)把當(dāng)前city天氣以純文本打印出來(lái)。
#!python3 #conding=utf-8 import requests,json,sys if len(sys.argv) < 2: print('Usage:tianqi.py location') sys.exit() #獲取參數(shù)城市 location =' '.join(sys.argv[1:]) apiUrl = 'http://wthrcdn.etouch.cn/weather_mini?city=%s' %(location) res = requests.get(apiUrl) res.raise_for_status() #獲取天氣json數(shù)據(jù) jsonDate = json.loads(res.text) tianQi = ((jsonDate['data'])['forecast']) print(location,'未來(lái)%s天天氣情況:'%(len(tianQi))) #循環(huán)輸出未來(lái)幾天天氣情況 for i in range(len(tianQi)): print(tianQi[i]['date'] + ' '+ tianQi[i]['high'] + ' ' + tianQi[i]['low'] + ' ' + tianQi[i]['type'])
26、假設(shè)要記錄在沒(méi)有自動(dòng)化的枯燥任務(wù)上花了多少時(shí)間。你沒(méi)有物理秒表,要為筆記本或智能手機(jī)找到一個(gè)免費(fèi)的秒表應(yīng)用,沒(méi)有廣告,且不會(huì)將你的瀏覽歷史發(fā)送給市場(chǎng)營(yíng)銷(xiāo)人員,又出乎意料地困難(在你同意的許可協(xié)議中,它說(shuō)它可以這樣做。你確實(shí)閱讀了許可協(xié)議,不是嗎?)。你可以自己用 Python 寫(xiě)一個(gè)簡(jiǎn)單的秒表程序。
#!/usr/bin/python36 #conding=utf8 import time print('請(qǐng)按回車(chē)鍵開(kāi)始,再次按下回車(chē)鍵記錄第二次計(jì)時(shí),按下Ctrl+C結(jié)束') 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圈,用時(shí):%s,總時(shí):%s'%(lapNum,lapTime,totalTime)) #strLap = '第%s圈'%lapNum #strlapTime = '用時(shí):%s'%lapTime #strtotalTime = '總時(shí):%s'%totalTime #print(strLap.ljust(8) + strlapTime.ljust(12) + strtotalTime.ljust(8)) lapNum += 1 lastTime = time.time() except KeyboardInterrupt: print('Done')
27、簡(jiǎn)單的倒計(jì)時(shí)程序,就像很難找到一個(gè)簡(jiǎn)單的秒表應(yīng)用程序一樣,也很難找到一個(gè)簡(jiǎn)單的倒計(jì)時(shí)程序。讓我們來(lái)寫(xiě)一個(gè)倒計(jì)時(shí)程序,在倒計(jì)時(shí)結(jié)束時(shí)報(bào)警。
#!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、假設(shè)你有一項(xiàng)無(wú)聊的工作,要調(diào)整數(shù)千張圖片的大小,并在每張圖片的角上增加一個(gè)小徽標(biāo)水印。使用基本的圖形程序,如 Paintbrush 或 Paint,完成這項(xiàng)工作需要很長(zhǎng)時(shí)間。像 Photoshop 這樣神奇的應(yīng)用程序可以批量處理,但這個(gè)軟件要花幾百美元。讓我們寫(xiě)一個(gè)腳本來(lái)完成工作。
的來(lái)說(shuō),程序應(yīng)該完成下面的事:
? 載入徽標(biāo)圖像。
? 循環(huán)遍歷工作目標(biāo)中的所有.png 和.jpg 文件。
? 檢查圖片是否寬于或高于 300 像素。
? 如果是,將寬度或高度中較大的一個(gè)減小為300 像素,并按比例縮小的另一維度。
? 在角上粘貼徽標(biāo)圖像。
? 將改變的圖像存入另一個(gè)文件夾。
#! 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、能夠確定鼠標(biāo)的位置,對(duì)于建立 GUI 自動(dòng)化腳本是很重要的。但光看屏幕,幾乎不能弄清楚像素的準(zhǔn)確坐標(biāo)。如果有一個(gè)程序在移動(dòng)鼠標(biāo)時(shí)隨時(shí)顯示 x y 坐標(biāo),就會(huì)很方便。
總的來(lái)說(shuō),你希望該程序做到:
獲得鼠標(biāo)當(dāng)前的 xy 坐標(biāo)。
當(dāng)鼠標(biāo)在屏幕上移動(dòng)時(shí),更新這些坐標(biāo)。
這意味著代碼需要做到下列事情:
調(diào)用函數(shù)取得當(dāng)前坐標(biāo)。
在屏幕上打印回退制服。刪除以前打印的坐標(biāo)。
處理異常。讓用戶能按鍵退出
#!python #conding=utf-8 import pyautogui print('請(qǐng)按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('退出!')