扩展本章中的多重剪贴板程序,增加一个delete 命令行参数,它将从shelf 中删除一个关键字。然后添加一个delete 命令行参数,它将删除所有关键字。
#! python3
# mcb.pyw - Saves and loads pieces of text to the clipboard.
# Usage: py.exe mcb.pyw save - Saves clipboard to keyword.
# py.exe mcb.pyw - Loads keyword to clipboard.
# py.exe mcb.pyw list - Loads all keywords to clipboard.
# py.exe mcb.pyw delete - delete keyword.
# py.exe mcb.pyw delete - delete list.
import shelve, pyperclip, sys
mcbShelf = shelve.open('mcb')
# save clipboard content.
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':
del mcbShelf[sys.argv[2]]
elif len(sys.argv) == 2:
# List keywords and load content.
if sys.argv[1].lower() == 'list':
pyperclip.copy(str(list(mcbShelf.keys())))
elif sys.argv[1] in mcbShelf:
pyperclip.copy(mcbShelf[sys.argv[1]])
elif sys.argv[1].lower() == 'delete':
mcbShelf.clear() # 清空后为[]
mcbShelf.close()
8.9.2 疯狂填词
创建一个疯狂填词(Mad Libs)程序,它将读入文本文件,并让用户在该文本文件中出现ADJECTIVE、NOUN、ADVERB 或VERB 等单词的地方,加上他们自己的文本。例如,一个文本文件(wenben.txt)可能看起来像这样:
The ADJECTIVE panda walked to the NOUN and then VERB. A nearby NOUN wasunaffected 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
# read in context
wbFile = open("wenben.txt")
wbcontent = wbFile.read()
print(wbcontent)
# replace content
inputct = input("Enter an adjective:\n")
Regex = re.compile(r'ADJECTIVE?')
wbcontent = Regex.sub(inputct, wbcontent)
inputct = input("Enter a noun:\n")
Regex = re.compile(r'NOUN')
wbcontent = Regex.sub(inputct, wbcontent, 1) # 对“NOUN”仅替换一次
inputct = input("Enter a verb:\n")
Regex = re.compile(r'VERB?')
wbcontent = Regex.sub(inputct, wbcontent)
inputct = input("Enter a noun:\n")
Regex = re.compile(r'NOUN?')
wbcontent = Regex.sub(inputct, wbcontent)
print(wbcontent)
outFile = open('outfile.txt', 'w')
outFile.write(wbcontent + '\n')
outFile.close()
8.9.3 正则表达式查找
编写一个程序,打开文件夹中所有的.txt 文件,查找匹配用户提供的正则表达式的所有行。结果应该打印到屏幕上。
# 查找文件夹中所有的.txt 文件,筛选出匹配用户提供的正则表达式的所有行
import os
import re
import sys
cwd = os.getcwd()
print(cwd)
# 查找文件夹中所有的.txt 文件
match1 = re.compile(r'.*\.txt$') # 创建匹配txt的正则
txtDirList = [] # 成功匹配
for i in os.listdir(cwd):
if match1.search(i) is not None: # 可以直接 if match1.search(i)
txtDirList.append(i)
print(txtDirList)
# 根据传入的参数来匹配需要行
print(sys.argv[1])
match2 = re.compile(sys.argv[1])
for i in txtDirList:
with open(i, 'r', encoding='utf-8') as txtFile:
txtLineList = txtFile.readlines()
for j in txtLineList:
if match2.search(j):
print(j + '\n')
https://www.cnblogs.com/wudongwei/p/9016994.html
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)