import shelve, pyperclip, sys
mcbShelf = shelve.open('mcb')
# sys.argv从程序外部获取参数的渠道,人机交互
# sys.argv[1]等于yyy.pyw XXX中的"XXX"
if len(sys.argv) == 3:
if sys.argv[1].lower() == 'save':
#将剪贴板的值放在“键”为sys.argv[2]的“值”上
mcbShelf[sys.argv[2]] = pyperclip.paste()
elif sys.argv[1].lower() == 'delete':
#删除shelf值中的某个“键”
if sys.argv[2] in mcbShelf:
del mcbShelf[sys.argv[2]]
elif len(sys.argv) == 2:
#查看当前插入了哪些“键”
if sys.argv[1].lower() == 'list':
pyperclip.copy(str(list(mcbShelf.keys())))
#将对应“键”的值复制到剪贴板上
elif sys.argv[1] in mcbShelf:
pyperclip.copy(mcbShelf[sys.argv[1]])
#将shelf值全部删除 #例 .\mcb.pyw delete
elif sys.argv[1].lower() == 'delete':
mcbShelf.clear()
mcbShelf.close()
The ADJECTIVE panda walked to the NOUN and then VERB. A nearby NOUN was unaffected by these events.
程序将找到这些出现的单词,并提示用户取代它们。
Enter an adjective:
silly
Enter a noun:
chandelier
Enter a verb:
screamed
Enter a noun:
pickup truck
以下的文本文件将被创建:
The silly panda walked to the chandelier and then screamed. A nearby pickup truck was unaffected by these events.
结果应该打印到屏幕上,并保存为一个新的文本文件。
import re
#读取892.txt内容
textA = open(r'.\892A.txt')
madLibsA = textA.read()
#构造正则,用findall方法得到搜索列表
strRegexs = re.compile(r'ADJECTIVE|NOUN|ADVERB|VERB')
listRegex = strRegexs.findall(madLibsA)
#使用sub方法,替换字符串madLibsB的特殊值
madLibsB = madLibsA
for i in listRegex:
if i[0] == 'A' :
tmp = input("Enter an " + i.lower() + ':\n')
else:
tmp = input("Enter a " + i.lower() + ':\n')
strRegex = re.compile(r'('+ i +')')
madLibsB = strRegex.sub(tmp, madLibsB, count=1)
#将数据写入B文件
textB = open(r'.\892B.txt', 'w')
textB.write(madLibsB)
textB.close()
import re, os
listDir = os.listdir()
listDirTxt = []
#for+if 进阶 初体验
listDirTxt = [i for i in listDir if '.txt' in i]
print(listDirTxt)
# for i in listDir:
# if '.txt' in i:
# listDirTxt.append(i)
aim = input("请输入您的正则表达式:\n")
strRegex = re.compile(r'('+ aim +')')
for i in listDirTxt:
txtFile = open('.\\'+ i +'')
txt = txtFile.readlines()
if strRegex.search(str(txt)):
print(txt)
txtFile = open(’.\\’+ i +’’)
strRegex = re.compile(r’(’+ aim +’)’)
AAA.sub(repl, string[, count = 0])
repl : 替换的字符串,也可为一个函数。
string : 要被查找替换的原始字符串。
count : 模式匹配后替换的最大次数,默认表示替换所有。