D
D
DarkWood2016-09-20 16:37:17
Python
DarkWood, 2016-09-20 16:37:17

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()

attachment.txt - storage for the list of replacements (attachmentid), new_1.txt - file where the replacement is made.
This code substitutes the entire list for each occurrence of the keyword. I would like the first occurrence of the keyword to be the first item of the list, for the second - the second, and so on:
Sometext
Keyword = [attachmentid=1923106]
More sometext
Keyword = [attachmentid=1923108]
etc
Please tell me how to fix this .
PS I don't know Python just a little less than at all. The code was compiled using Google and answers from StackOverflow.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander, 2016-09-20
@DarkWood

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 question

Ask a Question

731 491 924 answers to any question