1

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...

Georgy
  • 12,464
  • 7
  • 65
  • 73
Lightsaber
  • 13
  • 2

2 Answers2

1

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. 
Rakesh
  • 81,458
  • 17
  • 76
  • 113
  • Oh my god, BIG thanks to you! so i needed a temporary list in order to solve this, thanks, i learned something! – Lightsaber Jun 11 '19 at 13:39
0

You could use iter to do this as long as you text_list has exactly as many elements as sum(map(len, index_list))

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

index_list = [[1,2,3,4,5],[6,7,8],[9,10]]
text_list_iter = iter(text_list)
texts = [[next(text_list_iter) for _ in index] for index in index_list]

Output

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

But I am not sure if this is what you wanted to do. Maybe I am assuming some sort of ordering of index_list. The other answer I can think of is this list comprehension

texts_ = [[text_list[i-1] for i in l] for l in index_list]

Output

[['this', 'is', 'my', 'text', 'and'], ['it', 'should', 'be'], ['awesome', '.']]
Buckeye14Guy
  • 831
  • 6
  • 12