8.9.1
#! python3
# mcb.pyw - Saves and loads pieces of text to the clipboard.
# Usage: py.exe mcb.pyw save <keyword> - Saves clipboard to keyboard.
# py.exe mcb.pyw <keyword> - Loads keyword to clipboard.
# py.exe mcb.pyw list - Loads all keywords to clipboard.
# py.exe mcb.pyw delete <keyword> - Delete a keyword from the shelf.
# py.exe mcb.pyw delete - Delete all keywords.
import shelve, pyperclip, sys, os
os.chdir('D:\\Automate') # change a better cwd
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].lower() == 'delete':
mcbShelf.clear()
elif sys.argv[1] in mcbShelf:
pyperclip.copy(mcbShelf[sys.argv[1]])
mcbShelf.close()
這本書里附錄B的內(nèi)容我還是沒有看懂,按照書中的步驟,在“運(yùn)行”中輸入mcb.bat應(yīng)該是可以運(yùn)行程序的,可是做完后并沒有想要的效果,而是顯示沒有找到相關(guān)文件。
哪位大神可以指點(diǎn)一下?

運(yùn)行.jpg

運(yùn)行失敗.jpg
8.9.2
這個(gè)項(xiàng)目不是我自己想出來的,下面的代碼是他人的代碼修飾了一下,原始代碼的出處:https://www.cnblogs.com/Annaying/p/9142318.html
這段代碼中有兩處很值得我學(xué)習(xí):1. 如果單詞全部是大寫字母,對(duì)應(yīng)的正則表達(dá)式為'\w[A-Z]+';2. re.sub()方法的詳細(xì)使用技巧,特別是其中各個(gè)參數(shù)的用法(完整版解釋:https://blog.csdn.net/csucsgoat/article/details/81836712)。
import re, os
os.chdir('cwd')
# Open the file.
oldFile = open('sentence.txt','r')
words = oldFile.read()
oldFile.close()
print(words)
# Find the words written in capital letters, and replace them by new words.
oldRegex = re.compile(r'\w[A-Z]+') # the words written in capital letters
for content in oldRegex.findall(words):
replaceContent = input('Enter a %s:\n' % content)
regex = re.compile(content)
words = regex.sub(replaceContent, words, 1) # only one place to be replaced
print(words)
# Write in the new file.
newFile = open('sentence1.txt','w')
newFile.write(words)
newFile.close()
8.9.3
目的是尋找同一文件夾中,每個(gè)文本文檔中首字母為A的所有單詞。
其中os.listdir()方法,括號(hào)內(nèi)的參數(shù)不填路徑,默認(rèn)為此腳本所在的文件夾路徑。
open()函數(shù)的參數(shù)只需放入文件名字符串,默認(rèn)文件在此腳本所在的文件夾路徑。
import os, re
# The Regex: the first letter of the word is A.
capARegex = re.compile(r'[A]\w+')
for filename in os.listdir():
if filename.endswith('.txt'): # Loop the folder, open the file endwith txt.
fileObj = open(filename)
words = fileObj.read()
fileObj.close()
capA = capARegex.findall(words) # Find the specific words.
print('The words with captial A in ' + filename + ':')
print(capA)