为了账号安全,请及时绑定邮箱和手机立即绑定

如何映射文件中的不同文本

如何映射文件中的不同文本

互换的青春 2023-05-23 16:48:03
代码如下我需要用字典替换文件中的文本abc.txt 包含this is abc filecde.txt 包含this is cde file    {'abc':'123', 'cde':'456'}    all_files = ['abc.txt','cde.txt']    out_files = ['abc_output.txt','cde_output.txt']    read_dict = {}    for in_f, out_f in zip(all_files, out_files):        #print (in_f, out_f)        with open(in_f,'r') as read_file:            lines = read_file.readlines()        with open(out_f,'w+') as write_file:             #write_file.writelines(lines)            print(lines)我的出去['This is abc file']['This is cde file']预计出来['This is 123 file']['This is 456 file']
查看完整描述

2 回答

?
智慧大石

TA贡献1946条经验 获得超3个赞

mapping = {'abc':'123', 'cde':'456'}

all_files = ['abc.txt','cde.txt']

out_files = ['abc_output.txt','cde_output.txt']

read_dict = {}

for in_f, out_f in zip(all_files, out_files):

    #print (in_f, out_f)

    with open(in_f,'r') as read_file:

        lines = read_file.readlines()

    with open(out_f,'w+') as write_file:

        for line in lines:

            for key in mapping:

                line = line.replace(key, mapping[key])

            #write_file.writelines(line)


查看完整回答
反对 回复 2023-05-23
?
慕斯709654

TA贡献1840条经验 获得超5个赞

你也可以这样做


mapping = {'abc':'123', 'cde':'456'}

all_files = ['abc.txt','cde.txt']

out_files = ['abc_output.txt','cde_output.txt']

read_dict = {}

for in_f, out_f in zip(all_files, out_files):

    with open(in_f,'r') as read_file:

        lines = read_file.readlines()

    with open(out_f,'w+') as write_file:         

        for line in lines:    

            for key in mapping:

                line = line.replace(key, mapping[key])

            #write_file.writelines(line)


查看完整回答
反对 回复 2023-05-23
  • 2 回答
  • 0 关注
  • 143 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信