Мы ищем замену слова после каждого совпадения в списке слов для каждой строки в файле
Это говорит менеджер Сэм. Привет, как дела? Я в порядке. это директор Том. Приятно познакомиться, менеджер Сэм.
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()
Ожидаемый результат:
This is Manager *** speaking.Hello, how are you?
I am Fine. this is Director *** Nice to Meet you Manager ***
Но, выходной я получаю сейчас:
*** 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*** ?***