每天练练看,Python 编写一个程序,读取txt文件,把文件里面的内容实现“全部替换”功能,要求用函数封装程序,程序实现如图:
分析:
需要读取文件,把需要替换的字符串统计出来并且全部替换掉。
打开文件
输入需要替换的内容
输入需要替换的新内容
统计出所有的需要替换的字符串(count计数器来统计)
系统询问是否需要替换输入‘yes’or‘no’
如果输入‘yes’开始替换
输入‘no’则不替换
代码实现:def all_replace(file,rep_word,new_word):
f_read = open(file,encoding='utf-8')
list1 = []
count = 0
for each_line in f_read:
if rep_word in each_line:
count += each_line.count(rep_word)
each_line = each_line.replace(rep_word,new_word)
list1.append(each_line)
print('文件%s中共有%d个【%s】' % (file,count,rep_word))
print('您确定要把所有的【%s】替换为【%s】吗?' % (rep_word,new_word))
print('【YES/NO】:',end='')
acess = input()
if acess in ['yes','YES','Yes']:
f_write = open(file,'w',encoding='utf-8')
f_write.writelines(list1)
f_write.close()
print('替换成功')
if acess in ['NO','No','no']:
print('你已经输入了no,就是不替换')
f_read.close()
file = input('请输入文件名:')
rep_word = input('请输入需要替换的单词或字符:')
new_word = input('请输入新的单词或字符:')
all_replace(file,rep_word,new_word)