1 习题1.相对路径是相对于当前工作目录。 2.绝对路径从根文件夹开始,诸如/或C:\。 3.os.getcwd() 函数返回当前工作目录。os.chdir() 函数改变当前工作目录。 4.文件夹. 是当前文件夹,… 是父文件夹。 5.在C:\bacon\eggs\spam.txt 中,C:\bacon\eggs 是目录名,而spam.txt 是基本名称。 6.可以传递给open()函数的3 种“模式”参数是:字符串’r’ 对应读模式,‘w’ 对应写模式,‘a’ 对应添加模式。 7.如果已有的文件以写模式打开,原有内容会被删除并完全覆写。 8.read() 方法将文件的全部内容作为一个字符串返回。readlines() 返回一个字符串列表,其中每个字符串是文件内容中的一行。 9.shelf 值类似字典值,它有键和值,以及keys() 和 values() 方法,类似于同名 的字典方法。 2 实践项目2.2 疯狂填词 创建一个疯狂填词(Mad Libs)程序,它将读入文本文件,并让用户在该文本文件中出现ADJECTIVE、NOUN、ADVERB 或VERB 等单词的地方,加上他们自己的文本。例如,一个文本文件可能看起来像这样: 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 refilename = 'example.txt'with open(filename,'r') as o_ml: example_text = o_ml.readline() adjective=input('Enter an adjective:\n')noun=input('Enter a noun:\n')verb=input('Enter a verb:\n')adverb=input('Enter a adverb:\n')example_text=example_text.replace('ADJECTIVE',adjective)example_text=example_text.replace('NOUN',noun)example_text=example_text.replace('VERB',verb)example_text=example_text.replace('ADVERB',adverb)print('After:\n'+example_text)example_new=open('./example_new','w')example_new.write(example_text)example_new.close() - 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
2.3 正则表达式查找 编写一个程序,打开文件夹中所有的.txt 文件,查找匹配用户提供的正则表达式的所有行。结果应该打印到屏幕上。 import re, os# 编写一个正则表达式,匹配txt中所有小写5个字母的单词five_word = re.compile(r'\s[a-z]{5}\s')# 打开指定文件夹的所有txt文件,匹配所有行re_ans = []pathname = r'c:\users\hp\desktop'for filename in os.listdir(pathname): if filename.endswith('.txt'): with open(filename, 'r') as f: t_text = f.read() t_re_find = five_word.findall(t_text) re_ans += t_re_findprint(re_ans)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
|