Python编程快速上手
一、sys.exit()提前结束程序。
#提前终止程序
import sys
while True:
print('Type exit to exit.')
response = input()
if response == 'exit':
sys.exit()
else:
print('you typed'+response+'')
二、global语句
在函数中,如果被声明为global,则全局生效,影响函数外该变量值。
三、一个小程序,猜数字
#猜数字
import random
secretNumber=random.randint(1,20)
print('you thinking of 1-20')
for guessesTaken in range(1,7):
print('please input guess')
guess=int(input())
if secretNumber > guess:
print('you guess is low')
elif guess > secretNumber:
print('you guess is greate')
else:
break
if guess == secretNumber:
print('you are right,you guess in'+str(guessesTaken)+'guesses!')
else:
print('you are not right, this is '+str(secretNumber))
四、字典中的setdefault方法
字典存在则为字典中的值,不存在则为0
#setdefault()方法的使用
import pprint
message= "It is dangjingwei,this is myself,this is a boy"
count={}
for character in message:
count.setdefault(character,0)
count[character]=count[character]+1
pprint.pprint(count) ----漂亮的打印,如下,好看多了!!!
五、口令保管箱
Sys.argv[ ]其实就是一个列表,里边的项为用户输入的参数,关键就是要明白这参数是从程序外部输入的,而非代码本身的什么地方,要想看到它的效果就应该 将程序保存了,从外部来运行程序并给出参数。
pyperclip.copy() #将字符串放入粘贴板.
#口令管理
#ceshi.py
#!python3
import sys,pyperclip
PASSWORDS={
'djw':'1234567',
'email':'2921Djwjy',
'qq':'2921dyjhdjwjy'
}
if len(sys.argv)<2:
print('请输入两个值,文件名和需要查找密码的用户名')
sys.exit()
account=sys.argv[1]
if account in PASSWORDS.keys():
pyperclip.copy(PASSWORDS[account])
print('属于'+account+'的密码已经拷贝到剪贴板中')
else:
print('没有'+account+'的密码')
在win下进行批处理此文件ceshi.py
六、在wiki标记中添加无序列表
#!python3
import pyperclip
text=pyperclip.paste()
lines=text.split('\n')
for line in range(len(lines)):
lines[line]= '* '+lines[line]
text='\n'.join(lines)
pyperclip.copy(text)
七、电话号码提取程序(随便找一篇网页,复制后,运行程序,粘贴)
#!python3
import pyperclip, re
phoneRegex = re.compile(r'''( #这种compile是书中的写法
(\d{3}|\(\d{3}\))? #area code
(\s|-|\.)? #空格、点、或者-线
(\d{3}) #三个数字
(\s|-|\.) #空格、点、或者-线
(\d{4}) #最后四个数字
(\s*(ext|x|ext\.)\s*(\d{2,5}))?
)''', re.VERBOSE)
text = str(pyperclip.paste())
matches = []
for groups in phoneRegex.findall(text):
print(groups)
phoneNum = '-'.join([groups[1], groups[3], groups[5]])
if groups[8] != '':
phoneNum += ' x' + groups[8]
matches.append(phoneNum)
if len(matches):
pyperclip.copy('\n'.join(matches))
print('复制剪贴板电话')
print('\n'.join(matches))
else:
print('no phone numbers address found.')