Notes learning python "python programming quick start - let automate the tedious work of" Seven

Exercise Seven:
crazy lyrics: Create a crazy lyrics (Mad Libs) program that reads text files, and allows users to appear ADJECTIVE, NOUN, ADVERB or equal VERB word in the text file in place, coupled with their own text .

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:
		
Published 23 original articles · won praise 5 · Views 387

Guess you like

Origin blog.csdn.net/weixin_43287121/article/details/104483915