I have a book in txt format. I would like to create 2 new text: in the first, I would like to replace all occurencies of the string "Paul"
with Paul_1
, in the second with Paul_2
.
I wrote this code:
with open("book.txt", 'r') as original, \
open("book_1.txt", 'w') as mod1, \
open("book_2.txt", 'w') as mod2:
for line in original:
words = line.split()
for word in words:
s="Paul"
if(word == s):
mod1.write(word + "_1 ")
mod2.write(word + "_2 ")
else:
mod1.write(word + " ")
mod2.write(word + " ")
mod1.write("\n")
mod2.write("\n")
There is a problem, often some Paul
are skipped and therefore, in the end, I have in the same document both Paul
and Paul_1
(and Paul
and Paul_2
). Where is the problem?