Oct-17-2019, 04:10 AM
We are looking for replacing a word after each match in a list of words for each line in a file
Quote:This is Manager Sam speaking.Hello, how are you? I am Fine. this is Director Tom. Nice to Meet you Manager Sam.
import re f1=open('testinput.txt', 'r') f2=open('testoutput.txt', 'w') checkWords = ["Manager","Director"] repWords = ("*** ") for line in f1: i = 0 for i in range(len(checkWords)): # Find the next word after the search word list1 = re.compile(r'%s\s+((?:\w+(?:\s+!$)) {1})' %checkWords[i]).findall(line) checkWords = ','.join(list1) print(checkWords) line = line.replace(checkWords, repWords) print(line) f2.write(line) f1.close() f2.close()
Output:Expected Output:
This is Manager * speaking.Hello, how are you? I am Fine. this is Director * Nice to Meet you Manager ***
But, Output I am getting now: * T* h*** i*** s*** * i* s*** * M* a*** n*** a*** g*** e*** r*** * S* a*** m*** * s* p*** e*** a*** k*** i*** n*** g*** .* H* e*** l*** l*** o*** ,* * h*** o*** w*** * a* r*** e*** * y* o*** u*** ?***