Python 替换指定的内容(纯数字内容),然后将数字转换为密文,然后在文件中进行替换

实现功能:替换指定的内容(纯数字内容),然后将数字转换为密文,然后在文件中进行替换

 #将匹配到的数字转换成密文
    def func(s):
        result = ''
        for i in range(len(s)):
            result+= chr(int(dict_1[s[i]])+i) 
        return result 	
    
    import os
    import re
    def find_replace(path):
        for root,dirs,files in os.walk(path):
            file_error_count=0
            file_find_count =0
            file_error_list=[]
            for file in files:
                try:
                    with open(path+'\\'+file,'r+',encoding='ANSI') as fp:
                        content = fp.read()
                        p=re.findall(r'(?<=aaaaa\s)\d+(?=\s[bbbb])',content)#匹配特定的前边是aaa+空格,后边是空格+bbb的数字
                        print(p)
                        if p:#判断查到
                            for i in range(len(p)):
                                #content = content.replace(p[i],func(p[i]))#使用replace
                                content = re.sub(p[i],func(p[i]),content)#使用sub
                            file_find_count+=1
                        with open(path+'\\'+file,'w',encoding='ANSI') as fp1: #重新写入文件
                            fp1.write(content)
                except:
                    file_error_list.append(file)
                    file_error_count+=1
        print('打开错误文件个数',file_error_count)
        print('替换文件个数',file_find_count)
        return None

你可能感兴趣的:(个人python小程序)