首页 > 解决方案 > 使用 Python 脚本在文件中查找和替换没有输出

问题描述

不知何故,我在 new_code 文件中没有得到任何输出。

我正在尝试读取 file.txt 并根据字典值 (find_replace_dic) 进行更改。字典的键是要被字典值替换的单词。逻辑工作正常我尝试使用打印语句但不知何故 new_code 文件显示空白输出。

变量“new_word”包含每个 if 和 elif 条件的新更改。

with open('file.txt','r') as file, open ('model_testing_1.txt','w') as new_code:
    for line in file:
        word = line.replace('\n',"").split('.')[-1]
        if ':' in word:
            old_model = word.strip().split(':')[-1]
            old_model_s = old_model.strip()
            for key in find_replace_dic:
                if old_model_s == key:
                    new_word =  line.replace(old_model_s, find_replace_dic.get(key))
                    print(new_word)
        elif ':' not in word:
            for key in find_replace_dic:
                if word == key:
                    new_word =  line.replace(word, find_replace_dic.get(key))
                    print(new_word)         
                      
new_code.close()
file.close()

标签: pythonfiledictionaryreplacenested

解决方案


如果我正确地关注了帖子,那么源文件中每一行的逻辑都是这样的:

  • 拆分'.'上的行,获取最后一个元素
  • 如果最后一个元素包含':',则进一步拆分':'上的最后一个元素,得到最后一个元素
  • 如果元素在替换字典中,则从字典中替换元素
  • 输出替换元素的行

此代码遵循该逻辑:

data = '''
aaa1.bb:b1.ccc1.ddd1:eee1
aaa2.bb:b2.ccc2.ddd2:eee2
aaa3.bb:b3.ccc3.ddd3:eee3
aaa1:bbb1.ccc1:ddd1.eee1
aaa2:bbb2.ccc2:ddd2.eee2
'''.strip()

with open('file.txt','w') as f: f.write(data)  # test file

find_replace_dic = {'eee2':'zzz'}

################# Main Script ###################


with open('file.txt','r') as file, open ('model_testing_1.txt','w') as new_code:
    for line in file:
        word = line.replace('\n',"").split('.')[-1]
        if ':' in word:
            old_model = word.strip().split(':')[-1]
            old_model_s = old_model.strip()
            if old_model_s in find_replace_dic:
                line = line[:line.rindex(':')] + ':' + find_replace_dic[old_model_s]
        else: # ':' not in word
            if word in find_replace_dic:
                line = line[:line.rindex('.')] + '.' + find_replace_dic[word]
        print (line.strip())
        print (line.strip(), file=new_code)
                      
new_code.close()
file.close()

输出

aaa1.bb:b1.ccc1.ddd1:eee1
aaa2.bb:b2.ccc2.ddd2:zzz
aaa3.bb:b3.ccc3.ddd3:eee3
aaa1:bbb1.ccc1:ddd1.eee1
aaa2:bbb2.ccc2:ddd2.zzz

推荐阅读