《Python编程快速上手》---项目记录(1-7章)

第5章 列表

5.6 实践项目

5.6.2 列表到字典的函数,针对好玩游戏物品清单

stuff = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}
def displayInventory(inventory):
	print("Inventory:")
	item_total = 0
	for k, v in inventory.items():
		print(str(v) + ' ' + k)
		item_total += v
	print("Total number of items: " + str(item_total))


def addToInventory(inventory, addedItems):
	# your code goes here
	for addedItem in addedItems:
		if addedItem in inventory:
			inventory[addedItem]+=1
		else:
			inventory[addedItem]=1
	return inventory
	

inv = {'gold coin': 42, 'rope': 1}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
inv = addToInventory(inv,dragonLoot)
displayInventory(inv)

 

第6章 字符串

6.3 项目:口令保管箱

(1),解决附录B命令行运行.py文件的问题(B.2 在 Windows 上运行 Python 程序)

新建的.bat文件,其内容应该是:


@python C:\path\to\your\pythonScript.py %*
@pause

而非:

@py.exe C:\path\to\your\pythonScript.py %*

 “相当于”先保存了你要运行的.py文件的地址,而后通过python运行,

(2),切入正题:略(照着书写就成)

6.4 项目:在 Wiki 标记中添加无序列表

import pyperclip
text = pyperclip.paste()
# Separate lines and add stars.
lines = text.split('\n')
for i in range(len(lines)): # loop through all indexes for "lines" list
	lines[i] = '* ' + lines[i] # add star to each string in "lines" list
text = '\n'.join(lines)
pyperclip.copy(text)

6.7 实践项目:表格打印

 

#耗时0.5h
tableData = [['apples', 'oranges', 'cherries', 'banana'],
			['Alice', 'Bob', 'Carol', 'David'],
			['dogs', 'cats', 'moose', 'goose']]
			
def printTable():
	colWidths=[0]*len(tableData)
	i=0
	for tabdata in tableData:
		for data in tabdata:
			if(colWidths[i]

第7章 模式匹配和正则表达式

7.15 项目:电话号码和 E-mail 地址提取程序

import pyperclip, re
phoneRegex = re.compile(r'''(
	(\d{3}|\(\d{3}\))? 					# 区号
	(\s|-|\.)? 							# 分隔符
	(\d{3}) 							# 前三个数字
	(\s|-|\.) 							# 分隔符
	(\d{4}) 							# 后四个数字
	(\s*(ext|x|ext.)\s*(\d{2,5}))? 		# 扩展
	)''', re.VERBOSE)
	
# Create email regex.
emailRegex = re.compile(r'''(
	[a-zA-Z0-9._%+-]+ 		# 用户名
	@ 						# @ 标志
	[a-zA-Z0-9.-]+ 			# 域名
	(\.[a-zA-Z]{2,4}) 		# 最后的.+其他部分
	)''', re.VERBOSE)
text = str(pyperclip.paste())
matches = [] 
#查找电话号码
for groups in phoneRegex.findall(text):
	#1,3,5对应区号,前三个 后四个数字
	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 addresses found.')

注意:

剪切板上的内容,不应该是下面的一长串字符串,

Copiedtoclipboard:[email protected]@[email protected]@nostarch.com

否则则输出:

Copied to clipboard:
[email protected]
[email protected]
[email protected]
[email protected]

7.18.1 强口令检测

我的错误代码:

import pyperclip, re
def strong_sign(sign):
    if len(sign)<8:
	print("No\n")
    else:
	phoneNumRegex = re.compile(r'^\d+[a-zA-Z]+'|r'[a-zA-Z]+\d$'|r'[a-zA-Z]%d[a-zA-Z]')
        #你可能需要用多个正则表达式来测试该字符串,以保证它的强度。
        #但绝不是你加一个'|'就能匹配多个字符串的,
        #还有一点就是,search如果没找到要匹配的字符串,会返回None
	mo = phoneNumRegex.search('My number is 415-555-4242.')
	if(mo==None)
            print('No')
	else:
	    print('Yes')

正解1:

import re

text = str(input('输入一串口令:'))

def checkpw(text):
    flag = True
    if len(text) < 8:
        flag = False
    chpw1 = re.compile(r'[a-z]').search(text)
    chpw2 = re.compile(r'[0-9]+').search(text)
    chpw3 = re.compile(r'[A-Z]').search(text)
    if (chpw1 == None) or (chpw2 == None) or (chpw3 == None):
        flag = False
    if flag:
        print("口令正确")
    else:
        print("口令错误")

checkpw(text)

正解2:

import re
 
while True:
	pw = input('请输入口令:')
	if pw == 'q':
		break
	elif re.match(r'^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,}$',pw):
		print('强口令')
	else:
		print('若口令')
#知识点:
#?!作用:
#For example, Isaac (?!Asimov) will match 'Isaac ' only if it’s not followed by 'Asimov'.
#翻译:
#Isaac (?!Asimov)只有在后面没有'Asimov',才会匹配'Isaac'

#^                  匹配字符串的开始
#(?![0-9]+$)        表示此位置后,字符串结尾之前,所有的字符不能全由数字组成
#(?![a-zA-Z]+$)     表示此位置后,字符串结尾之前,所有的字符不能全由字母组成
#[0-9A-Za-z]{8,}$   表示匹配整个字符串由  >=8位  数字和字母组成

7.18.2 strip()的正则表达式版本

strip()作用:删除字符串 开头或者结尾 的  空格(默认情况),或者指定字符

import re

def re_strip(s, t=r'\s'):
    t_format = r'^%s*|%s*$' % (t, t)
    s_re = re.compile(t_format)
    s = s_re.sub('',s)
    return s

print(re_strip('aadasdfsaaa','a'))
print(re_strip('  dafsdfa sadfasd  '))

编译结果:
dasdfs
dafsdfa sadfasd

 

你可能感兴趣的:(《Python编程快速上手》)