《Python编程快速上手》8.9 实践项目

8.9.1 扩展多重剪贴板

 1 #! python3
 2 # mcb.pyw - Saves and loads pieces of text to the clipboard.
 3 # Usage: py.exe mcb.pyw save <keyword> - Saves clipboard to keyword.
 4 #        py.exe mcb.pyw <keyword> - Loads keyword to clipboard.
 5 #        py.exe mcb.pyw list - Loads all keywords to clipboard.
 6 
 7 import shelve, pyperclip, sys
 8 
 9 mcbShelf = shelve.open('mcb')
10 
11 # Save clipboard content.
12 if len(sys.argv) == 3:
13     # 保存
14     if sys.argv[1].lower() == 'save':
15         mcbShelf[sys.argv[2]] = pyperclip.paste()
16     # 删除指定关键字
17     elif sys.argv[1].lower() == 'delete' and sys.argv[2] in mcbShelf:
18         del mcbShelf[sys.argv[2]]
19         
20 elif len(sys.argv) == 2:
21     # List keywords and load content.
22     if sys.argv[1].lower() == 'list':
23         pyperclip.copy(str(list(mcbShelf.keys())))
24     # 清空字典
25     elif sys.argv[1].lower() == 'delete':
26         mcbShelf.clear()
27     elif sys.argv[1] in mcbShelf:
28         pyperclip.copy(mcbShelf[sys.argv[1]])
29 
30 mcbShelf.close()

8.9.2 疯狂填词

用repalce()或re.sub()都可以

 1 #! python3
 2 # Mad Libs
 3 
 4 import re
 5 
 6 filename = input('Enter filename:\n')
 7 # 读入文本文件
 8 file = open(filename)
 9 text = file.read()
10 file.close()
11 # 找到文中出现的单词,然后替换
12 textr = re.compile(r'ADJECTIVE|NOUN|ADVERB|VERB+').findall(text)
13 for names in textr:
14     if names[0] == 'A':
15         sub = input('Enter an %s:\n' % names)
16     else:
17         sub = input('Enter a %s:\n' % names)
18     text = re.sub(r'ADJECTIVE|NOUN|ADVERB|VERB+',sub,text,1)
19 # 保存为新的文本文件
20 file = open('new'+filename,'w')
21 file.write(text)
22 file.close()
23 # 打印
24 print(text)

8.9.3 正则表达式查找

 1 import os,re
 2 # 输入路径
 3 path = input('Enter the path:\n')
 4 files = os.listdir(path)
 5 # 输入正则表达式
 6 regex = input('Enter the regex:\n')
 7 regex1 = re.compile(r'' + regex + '')
 8 # 查找
 9 for filenames in files:
10     if '.txt' in filenames:
11         txts = open(os.path.join(path,filenames)).readlines()
12         for lines in txts:
13             if regex1.search(lines):
14                 print(lines)

猜你喜欢

转载自www.cnblogs.com/eugene-21/p/9428083.html
今日推荐