Python 编写一个程序,实现“全部替换”功能

Python学习笔记3字数 862阅读模式

每天练练看,Python 编写一个程序,读取txt文件,把文件里面的内容实现“全部替换”功能,要求用函数封装程序,程序实现如图:

Python 编写一个程序,实现“全部替换”功能

分析:

需要读取文件,把需要替换的字符串统计出来并且全部替换掉。

打开文件

输入需要替换的内容

输入需要替换的新内容

统计出所有的需要替换的字符串(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)

 

weinxin
我的微信
微信公众号
关注大鸟博客公众号
 
大鸟
评论  3  访客  2  作者  1
    • 奶爸de笔记
      奶爸de笔记 7

      最近几年python挺火的。

        • 大鸟
          大鸟

          @ 奶爸de笔记 火是很火,但是难学是真的,特别对自学的人来说。

        • 云点SEO
          云点SEO 6

          有才

        匿名

        发表评论

        匿名网友

        :?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

        确定