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('退出!')


