第08章课后项目

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的内容我还是没有看懂,按照书中的步骤,在“运行”中输入mcb.bat应该是可以运行程序的,可是做完后并没有想要的效果,而是显示没有找到相关文件。

哪位大神可以指点一下?

运行.jpg

运行失败.jpg

8.9.2
这个项目不是我自己想出来的,下面的代码是他人的代码修饰了一下,原始代码的出处:https://www.cnblogs.com/Annaying/p/9142318.html
这段代码中有两处很值得我学习:1. 如果单词全部是大写字母,对应的正则表达式为'\w[A-Z]+';2. re.sub()方法的详细使用技巧,特别是其中各个参数的用法(完整版解释: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
目的是寻找同一文件夹中,每个文本文档中首字母为A的所有单词。
其中os.listdir()方法,括号内的参数不填路径,默认为此脚本所在的文件夹路径。
open()函数的参数只需放入文件名字符串,默认文件在此脚本所在的文件夹路径。

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)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。