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)