You didn't specified if the result must be in another file, but I assumed so.
Assuming that foo.txt
is the file containing the patter to match (that is <text = " ">
), and replacements.txt
contains the replacements to put, line by line, this is how to do this task.
import re
with open('foo.txt') as f:
lines = [line.strip() for line in f.readlines()]
with open('replacements.txt') as f:
replacements = [line.strip() for line in f.readlines()]
First we read the contents of the files (stripping every line from whitespaces and endline character).
j = 0
for i, line in enumerate(lines):
result = re.match('<text = " ">', line)
if result and j < len(replacements):
lines[i] = replacements[j]
j += 1
Then we setup a counter for the replacements array, and for every line we search the string to replace.
If it's found and we have replacements to put, we proceed to change that line with the j-th element.
lines = [line + '
' for line in lines]
with open('foo_modified.txt', 'w') as f:
f.writelines(lines)
Then we join together the modified lines (adding manually the endline character, stripped before), and we write it out in another file.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…