8.9.1 shelf 的删除-多重剪贴板
import shelve, pyperclip, sys
mcbShelf = shelve.open('F:\\python\\mcb')
if len(sys.argv) == 3 :
if sys.argv[1].lower() == 'save' :
mcbShelf[sys.argv[2]] = pyperclip.paste()
print(pyperclip.paste())
elif sys.argv[1].lower() == 'delete':
del mcbShelf[sys.argv[2]] #delete one item
print('delete1')
elif len(sys.argv) == 2 :
if sys.argv[1].lower() == 'list' :
pyperclip.copy(str(list(mcbShelf.keys())))
print(str(list(mcbShelf.keys())))
print(str(list(mcbShelf.values())))
elif sys.argv[1] in mcbShelf:
pyperclip.copy(mcbShelf[sys.argv[1]])
print(mcbShelf[sys.argv[1]])
elif sys.argv[1].lower() == 'delete':
mcbShelf.clear() #delele all
print('delete2')
mcbShelf.close()
8 .9.2 疯狂填词
import re
readFile = open('F:\\python\\madlibs.txt')
readContent = readFile.read()
readFile.close()
wordRegex = re.compile(r'ADJECTIVE|NOUN|ADVERB|VERB') #正则表达式
print(readContent)
searchResult = wordRegex.findall(readContent)
inputResult=[]
for i in searchResult :
if i == 'ADJECTIVE' :
print('Enter an adjective:')
inputResult.append(input())
if i == 'NOUN' :
print('Enter a noun:')
inputResult.append(input())
if i == 'ADVERB' :
print('Enter a verb:')
inputResult.append(input())
if i == 'VERB' :
print('Enter an adverb:')
inputResult.append(input())
writeContent = wordRegex.sub('%s', readContent) #通配符插入
writeFile = open('F:\\python\\madlibs_result.txt', 'w')
writeFile.write(writeContent%(tuple(inputResult))) #通配符替换, tuple可以但是list不可以
print(writeContent%(tuple(inputResult)))
writeFile.close()
8.9.3 正则表达式查找 - 可以扩展 - grep
import os,sys,re
def viewall(path):
path = os.path.abspath(path)
for i in os.listdir(path): #listdir() return relpath only
file = os.path.join(path, i) #join to get abspath
if os.path.isdir(file):
viewall(file)
elif os.path.basename(file).endswith('.txt'):
checkfile(file)
def checkfile(file):
file = os.path.abspath(file)
fileContent = open(file).readlines()
for line in fileContent:
if regex.search(line, re.I) != None :
print(file + ':' + line)
if len(sys.argv) != 3 :
print('wrong format')
sys.exit()
rootPath = sys.argv[1]
regex = re.compile(sys.argv[2])
if not os.path.exists(rootPath):
print('invalid path')
sys.exit()
if os.path.isdir(rootPath):
viewall(rootPath)
elif os.path.isfile(rootPath) and os.path.basename(rootPath).endswith('.txt'):
checkfile(rootPath)