Search code examples
pythonpython-2.7linecache

Replacing numbers in a list of lists with corresponding lines from a text file


I have a big text file like this (without the blank space in between words but every word in each line):

this

is

my

text

and

it

should

be

awesome

.

And I have also a list like this:

index_list = [[1,2,3,4,5],[6,7,8][9,10]]

Now I want to replace every element of each list with the corresponding index line of my text file, so the expected answer would be:

new_list = [[this, is, my, text, and],[it, should, be],[awesome, .]

I tried a nasty workaround with two for loops with a range function that was way too complicated (so I thought). Then I tried it with linecache.getline, but that also has some issues:

import linecache

new_list = []

for l in index_list:
       for j in l:
             new_list.append(linecache.getline('text_list', j))

This does produce only one big list, which I don't want. Also, after every word I get a bad \n which I do not get when I open the file with b = open('text_list', 'r').read.splitlines() but I don't know how to implement this in my replace function (or create, rather) so I don't get [['this\n' ,'is\n' , etc...


Solution

  • You are very close. Just use a temp list and the append that to the main list. Also you can use str.strip to remove newline char.

    Ex:

    import linecache
    
    new_list = []
    index_list = [[1,2,3,4,5],[6,7,8],[9,10]]
    for l in index_list:
        temp = []   #Temp List
        for j in l:
            temp.append(linecache.getline('text_list', j).strip())
        new_list.append(temp)       #Append to main list.