项目
ch6 字符串操作
口令保管箱
完整代码
#! python3 在windows上运行python程序的第一行代码
# pw.py - An insecure password locker program.
PASSWORDS = {'email': 'abhjihsu3hhugdehndohhk',
'blog': 'asfhuefbjksdfsgwe',
'luggage': '24387247'}
import sys, pyperclip
if len(sys.argv) < 2:
print('Usage: python pw.py [account] - copy account password')
sys.exit()
account = sys.argv[1] # first command line arg is the account name
if account in PASSWORDS:
pyperclip.copy(PASSWORDS[account])
print('Password for ' + account + 'copied to clipboard.')
else:
print('There is no account named ' + account)
重要内容
对于sys.argv的理解
参考https://www.cnblogs.com/aland-1415/p/6613449.html
sys.argv[]是用来获取命令行输入的参数的(参数和参数之间空格区分)。
其中,sys.argv[0]表示代码本身文件路径。
从参数1开始,表示获取的参数了
实现步骤
-
按下Win+R或者在全部程序里面搜索“运行”
-
输入cmd进入控制台命令窗口
-
进入代码文件所在的目录
-
将账号的口令复制到剪贴板
完成操作,email的密码复制到了剪贴板,直接粘贴就可以得到:abhjihsu3hhugdehndohhk
在Wiki标记中添加无序列表
在这里插入代码片
ch7模式匹配与正则表达式
电话号码和E-mail地址提取程序
代码理解
正则表达式的理解
-可选的区号 (\d{3}|(\d{3}))? 表示要么是三个数字要么是括号内的三个数字,应该使用管道字符进行连接
- 电话分割字符可以是空格(\S)、短横(-)或者句点(.)也应该使用管道字符进行连接
- 可选的分机号包括任意数目的空格接着是ext、x或者ext,再接着就是2到5位的数字
- 邮箱地址的用户部分可以是一个或者多个字符,其中字符包括:小写和大写字符、数字、句点、下划线、百分号、加号或者短横,所以写作:[a-zA-Z0-0._%±]
在剪贴板文本中找到所有匹配
- pyperclip.paste()将取得一个字符串,内容就是剪贴板上面的文本
- findall()正则表达方法返回一个元组的列表
完整代码
#! python3
# phoneAndEmail.py - Finds phone numbers and email address on the clipboard.
import pyperclip, re
# Create phone regex
phoneRegex = re.compile('''(
(\d{3}|\(\d{3}\))? #area code
(\s|-|\.)? #separator
(\d{3}) #first 3 digits
(\s| -|\.) #separator
(\d{4}) #last 4 digits
(\s*(ext|x|ext.)\s*(\d{2,5}))? #extension
)''', re.VERBOSE)
# Create email regex
emailRegex = re.compile('''(
[a-zA-Z0-0._%+-]+ #username
@ #@ symbol
[a-zA-Z0-0._-]+ #domain name
(\.[a-zA-Z]{2,4}) #dot-something
)''', re.VERBOSE)
# Find matches in clipboard text.
text = str(pyperclip.paste())
matches = []
for groups in phoneRegex.findall(text):
phoneNum = '-'.join([groups[1], groups[3], groups[5]])
if groups[8] != '':
phoneNum += ' x' + groups[8]
matches.append(phoneNum)
for groups in emailRegex.findall(text):
matches.append(groups[0])
# Copy results to the clipboard.
if len(matches) > 0:
pyperclip.copy('\n'.join(matches))
print('Copied to clipboard:')
print('\n'.join(matches))
else:
print('No phone numbers or email address found')
强口令检测
实现功能
确保输入的口令字符串是强口令:长度不少于8个字符,同时包含大小写字符,至少有一个数字。
完整代码
#! python
# strong password
import re
password = str(input('输入一串口令:'))
def strong(text):
flag = True
if len(text) < 8:
flag = False
cha1 = re.compile(r'[a-z]').search(text)
cha2 = re.compile(r'[A-Z]').search(text)
cha3 = re.compile(r'[0-9]+').search(text)
print(cha1)
print(cha2)
print(cha3)
if (cha1 == None) or (cha2 == None) or (cha3 == None):
flag = False
print(flag)
if flag:
print('口令格式正确')
else:
print('口令格式错误')
strong(password)
ch8 读写文件
生成随机的测验试卷文件
关键代码解读以及关键步骤
-
将测验数据保存在一个字典中
-
创建测验文件,并打乱问题次序**random.shuffle():**将一个列表中的元素打乱,在本项目中可以随机调整问题和多重选项的次序
占位符%s、%d
占位符%s表示格式化一个对象为字符;
%d表示格式化一个对象为数字
占位符都会被在%后代表是字符或者数字的对象取代 -
创建答案选项
-
将内容写入测验试卷和答案文件
完整代码
# ! python3
# randomQuizGenerator.py - Creates quizzes with questions and answers in
# random order, along with the answer key.
import random
# The quiz data. Keys are states and values are their capitals.
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'}
# Generate 35 quiz files.
for quizNum in range(35):
# Create the quiz and answer key files.
quizFile = open('captalsquiz%s.txt' % (quizNum + 1), 'w')
answerKeyFile = open('captalsquiz_answers%s.txt' % (quizNum + 1), 'w')
# Write out the header for the quiz.
quizFile.write('Name:\n\nDate:\n\nPeriod:\n\n')
quizFile.write((' ' * 20) + 'State Capitals Quiz (Form %s)' % (quizNum + 1))
quizFile.write('\n\n')
# Shuffle the order of the states.
states = list(capitals.keys())
random.shuffle(states)
# Loop through all 50 states, making a question for each.
for questionNum in range(50):
# Get right and wrong answers.
correctAnswer = capitals[states[questionNum]]
wrongAnswers = list(capitals.values())
del wrongAnswers[wrongAnswers.index(correctAnswer)]
wrongAnswers = random.sample(wrongAnswers, 3)
answerOptions = wrongAnswers + [correctAnswer]
random.shuffle(answerOptions)
# Write the question and the answer options to the quiz file.
quizFile.write('%s. What is the capital of %s?\n' % (questionNum + 1, states[questionNum]))
for i in range(4):
quizFile.write(' %s. %s\n' % ('ABCD'[i], answerOptions[i]))
quizFile.write('\n')
# Write the answer key to a file.
answerKeyFile.write('%s. %s\n' % (questionNum + 1, 'ABCD'[answerOptions.index(correctAnswer)]))
quizFile.close()
answerKeyFile.close()