Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find and replace multiple words in a file python

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_text'))
f1.close()
f2.close()

But I am not able to figure out how to replace multiple words with respective new words. In this example if I want to find some words like (old_text1,old_text2,old_text3,old_text4) and replace by its respective new words (new_text1,new_text2,new_text3,new_text4).

Thanks in advance!

like image 821
bikuser Avatar asked Dec 01 '22 10:12

bikuser


2 Answers

You can iterate over your check words and toReplace words using zip and then replace.

Ex:

checkWords = ("old_text1","old_text2","old_text3","old_text4")
repWords = ("new_text1","new_text2","new_text3","new_text4")

for line in f1:
    for check, rep in zip(checkWords, repWords):
        line = line.replace(check, rep)
    f2.write(line)
f1.close()
f2.close()
like image 171
Rakesh Avatar answered Dec 03 '22 23:12

Rakesh


It's easy use re module

import re
s = "old_text1 old_text2"
s1 = re.sub("old_text" , "new_text" , s)

output

'new_text1 new_text2'

re.sub substitute the old text with the new text re.sub doc https://docs.python.org/3.7/library/re.html#re.sub

like image 32
aman5319 Avatar answered Dec 04 '22 00:12

aman5319