python编程快速上手——第八章编程实践

8.9.1扩展多重剪贴板

#!python3
#mcb.pyw - Saves and loads pieces of text to the clipboard.

import shelve,pyperclip,sys

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' and sys.argv[2] in mcbShelf.keys():
	del mcbShelf[sys.argv[2]]
	print('delete: %s'%(sys.argv[2]))
elif len(sys.argv)==2:
	if sys.argv[1].lower() == 'list':
		pyperclip.copy(str(list(mcbShelf.keys())))
		print(list(mcbShelf.keys()))
	elif sys.argv[1] in mcbShelf:
		pyperclip.copy(mcbShelf[sys.argv[1]])
		print(mcbShelf[sys.argv[1]])
	elif sys.argv[1].lower() == 'delete':
		for item in  mcbShelf.keys():
			del mcbShelf[item]
			print('delete: %s'%(item))

		
mcbShelf.close()

8.9.2疯狂填词

#!python3

import re,os

fileName = input('请输入待操作的文件名:')
while  fileName != '' and os.path.isfile(fileName) != True: #检查输入文件路径是否正确
	fileName = input('输入文件路径错误,请重新输入文件名:')


with open(fileName,'r') as fileOpen,open(os.path.join(os.path.dirname(fileName),'new'+os.path.basename(fileName)),'w') as fileWrite:
	text = fileOpen.read()

	oldwords = []

	word = input('请输入被替换的单词(按回车结束输入):')
	while word != '':
		oldwords.append(word)
		word = input('请输入被替换的单词(按回车结束输入):')
		word.replace('\\',r'\\')  #避免输入出现反斜杠

	print('收集被替换的单词完毕,现在开始进行单词替换')

	for word in oldwords:
		newword = input('Enter an %s\n'%word)
		newword = newword.replace('\\',r'\\')
		print(newword)
		replaceRegex = re.compile(word)
		newtext = replaceRegex.sub(newword,text)  #正则替换
		print('替换单词:%s 完成'%word)

	fileWrite.write(newtext)
	print(newtext)

8.9.3正则表达式查找

#!python3

import os,re

filePath = input('请输入待查找的文件夹路径:')

if os.path.isdir(filePath) == False:
	raise Exception('filePath is invalid.')

Regex = input('请输入正则表达式:')
Regex = Regex.replace('\\',r'\\')  #防止用户输入\
fileRegex = re.compile(Regex)


for folderName,subfolders,filenames in os.walk(filePath):
	for filename in filenames:
		if filename.endswith('.txt') == True:
			with open(os.path.join(folderName,filename),'r') as fileRead:
				lines = fileRead.readlines()
				for line in lines:
					if fileRegex.search(line) != None:
						print(filename+' : '+line)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值