find and replace multiple words in a file python

后端 未结 5 1876
生来不讨喜
生来不讨喜 2020-12-30 18:54

I took example code from here.

f1 = open(\'file1.txt\', \'r\')
f2 = open(\'file2.txt\', \'w\')
for line in f1:
    f2.write(line.replace(\'old_text\', \'new         


        
5条回答
  •  既然无缘
    2020-12-30 19:25

    You can replace the content of a text or file with sub from the regex module (re):

    def replace_content(dict_replace, target):
        """Based on dict, replaces key with the value on the target."""
    
        for check, replacer in list(dict_replace.items()):
            target = sub(check, replacer, target)
    
        return target
    

    Or just with str.replace which does not need from re import sub:

    def replace_content(dict_replace, target):
        """Based on dict, replaces key with the value on the target."""
    
        for check, replacer in list(dict_replace.items()):
            target = target.replace(check, replacer)
    
        return target
    

    Here's the full implementation:

    from re import sub
    from os.path import abspath, realpath, join, dirname
    
    file = abspath(join(dirname(__file__), 'foo.txt'))
    file_open = open(file, 'r')
    file_read = file_open.read()
    file_open.close()
    
    new_file = abspath(join(dirname(__file__), 'bar.txt'))
    new_file_open = open(new_file, 'w')
    
    
    def replace_content(dict_replace, target):
        """Based on dict, replaces key with the value on the target."""
    
        for check, replacer in list(dict_replace.items()):
            target = sub(check, replacer, target)
            # target = target.replace(check, replacer)
    
        return target
    
    
    # check : replacer
    dict_replace = {
        'ipsum': 'XXXXXXX',
        'amet,': '***********',
        'dolor': '$$$$$'
    }
    
    new_content = replace_content(dict_replace, file_read)
    new_file_open.write(new_content)
    new_file_open.close()
    
    # Test
    print(file_read)
    # Lorem ipsum dolor sit amet, lorem ipsum dolor sit amet
    
    print(new_content)
    # Lorem XXXXXXX $$$$$ sit *********** lorem XXXXXXX $$$$$ sit amet
    

提交回复
热议问题