学习python笔记《python编程快速上手-让繁琐工作自动化》之七

练习七:
疯狂填词:创建一个疯狂填词(Mad Libs)程序,它将读入文本文件,并让用户在该文本文件中出现 ADJECTIVE、NOUN、ADVERB 或 VERB 等单词的地方,加上他们自己的文本。

strl='The ADJECTIVE panda walked to the NOUN and then VERB. A nearby NOUN was unaffected by these events.'

def madlib(strl):
	newstr=strl
	find_str=['ADJECTIVE','NOUN','ADVERB','VERB']
	for i in find_str:
		print('请输入替换{}的字符串'.format(i))
		user_input=input('请输入:')
		newstr=re.sub(i,user_input,newstr)#循环替换赋值
	print(newstr)
	return newstr
'正则表达式查找编写一个程序,打开文件夹中所有的.txt 文件,查找匹配用户提供的正则表达式的所有行。结果应该打印到屏幕上。'
def find_line(file,pattern):
#判断传入目录是否存在
	if os.path.exists(file):
		file_txt=[i for i in os.listdir(file) if i.endswith('.txt')]#输出文件夹内所有txt文件
		if file_txt != []:#如果列表不为空
			for txt in file_txt:#迭代选取文件名
				path=os.path.join(file,txt)#组成目录
				with open(path,'r') as fp:#建立文件对象
					for k in fp:
						pat=re.findall(pattern,k)
						if pat !=[]:
							print(k)
	文件读取的几种方式:
	file.read()返回为整个文档的字符串
	file.readline()每次调用返回一行的字符串
	file.readlines()返回按行组成的列表
	##最好的文件读取方式,但不一定是最适合的
	with open(filepath,'r') as fp:
		for i in fp:
		
发布了23 篇原创文章 · 获赞 5 · 访问量 387

猜你喜欢

转载自blog.csdn.net/weixin_43287121/article/details/104483915