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

代码如下

我需要用字典替换文件中的文本

  • abc.txt 包含this is abc file

  • cde.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']


互换的青春
浏览 144回答 2
2回答

智慧大石

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)

慕斯709654

你也可以这样做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)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python