find and replace multiple words in a file python

后端 未结 5 1905
生来不讨喜
生来不讨喜 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:26

    I've learned that this script works very well and much faster then the ones that i've used in the past.

    import re
    
    def word_replace(text, replace_dict):
    rc = re.compile(r"[A-Za-z_]\w*")
    
    def translate(match):
        word = match.group(0).lower()
        print(word)
        return replace_dict.get(word, word)
    
    return rc.sub(translate, text)
    
    old_text = open('YOUR_FILE').read()
    
    replace_dict = {
    "old_word1" : 'new_word1',
    "old_word2" : 'new_word2',
    "old_word3" : 'new_word3',
    "old_word4" : 'new_word4',
    "old_word5" : 'new_word5'
    
     }                            # {"words_to_find" : 'word_to_replace'}
    
    output = word_replace(old_text, replace_dict)
    f = open("YOUR_FILE", 'w')                   #what file you want to write to
    f.write(output)                              #write to the file
    print(output)                                #check that it worked in the console 
    

提交回复
热议问题