How do I make each sentence into a nested list?

72 views Asked by At

I'm working with a text file that looks like this; (The words are in Swedish)

['1', 'Denna', '_', 'DET', 'DT', 'UTR|SIN|DEF', '2', 'DT', '_', '_\n']
['2', 'predestination', '_', 'NOUN', 'NN', 'UTR|SIN|IND|NOM', '7', 'SS', '_', '_\n']
['3', 'till', '_', 'ADP', 'PP', '_', '2', 'ET', '_', '_\n']
['4', 'en', '_', 'DET', 'DT', 'UTR|SIN|IND', '6', 'DT', '_', '_\n']
.....

There are about 500 sentences of various lenghts; each line describes one word. The first list element gives the word's position in the sentence.

I need my program to make a nested list from the entries for each sentence (one sub-list for each sentence). Every new sentence starts with position '1', and they are separated by empty lines. At the moment all my lines are in one list.

I would like to do something like:

l = []
for line in list:
    if line[0] == '1':
        l.append(line)

... then append every line that follows until it reaches '1' again, where I start with a new sub-list.

Some ides on how to do it? How could I make this recursive?

1

There are 1 answers

0
Prune On

This is not a naturally recursive process; it's iterative. A simple loop will do the job.

alla = []
forst = True
for line in list:
    if line[1] == '1':
        # ny mening
        if not forst:
            alla.append(mening)
        forst = False
        mening = []

    mening.append(line)

Since the trigger for each append is the start of the sentence, you still have one sentence left to add. I'll leave that part for you to do. :-)