Answer the question
In order to leave comments, you need to log in
Python: Replacing a keyword with values from a list in order?
Hello.
There is a text file with a keyword. It looks something like this:
Sometext
Keyword
More sometext
Keyword
etc
There is also a list (another text file) from which I want to get keyword substitutions. The keyword is the same, the values for the replacement are all different.
List view with replacements:
[attachmentid=1923106]
[attachmentid=1923108]
[attachmentid=1923110]
[attachmentid=1923112]
[attachmentid=1923114]
and so on.
I compiled the following Python script (version 3.5.1):
list = []
with open('d:/attachment.txt','r') as inf:
list = inf.read()
file = open('d:/new_1.txt', 'r')
text = file.read()
num_of_words = text.count('Image')
for i in range(0, num_of_words):
text = text.replace('Image', list, 1)
file.close()
file = open('d:/new_1.txt', 'w')
file.write(text)
file.close()
Answer the question
In order to leave comments, you need to log in
In the line
You need to add an index - so that at each step only the element with this index is substituted, and not the whole list:
But this will work fine only if the number of replacement lines is guaranteed not less than the number of places to replace. Otherwise, you will get an error.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question