【问题标题】:No output for Find and Replace in Files using Python Script使用 Python 脚本在文件中查找和替换没有输出
【发布时间】:2020-08-29 18:02:10
【问题描述】:

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

我正在尝试读取 file.txt 并根据字典值 (find_replace_dic) 进行更改。字典的键是要被字典值替换的单词。逻辑工作正常我尝试使用 print 语句,但不知何故 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()

【问题讨论】:

  • 使用with时不需要.close()
  • 你也可以用if word in find_replace_dic代替整个for循环
  • @MZ 遗憾的是它仍然没有返回任何内容。
  • @MZ 添加条件是因为有些单词有'.'在它们之前,其中一些将在冒号之后被选中,而不是其他。
  • 你确定它应该打印一些东西吗?你检查了吗

标签: python file dictionary replace nested


【解决方案1】:

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

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

这段代码遵循这个逻辑:

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

【讨论】:

  • 目前还存在多种其他情况。但这是正确的。假设有些行和单词在我们的字典中没有键/值,所以我们也希望它们保持原样 - 这意味着无需进行任何更改,只需复制原始行并将其粘贴到新文件中即可。
猜你喜欢
  • 1970-01-01
  • 2011-06-12
  • 2019-07-30
  • 2017-02-06
  • 2017-03-10
  • 1970-01-01
  • 2013-05-27
  • 2011-04-25
  • 1970-01-01
相关资源
最近更新 更多