write a text file from list of tuple in different columns separated by newline

Viewed 82

I have list of tuple within a list which is list of sentence, pos tagged corresponding word in tuple.

[[('This', 'DT'), ('is', 'VBZ'), ('the', 'DT'), ('house', 'NN')], 
[('This', 'DT'), ('is', 'VBZ'), ('the', 'DT'), ('car', 'NN')], 
[('This', 'DT'), ('is', 'VBZ'), ('the', 'DT'), ('dog', 'NN')]]

I want to write it into text file. Expected output :

This DT
is VBZ
the DT
house NN

This DT
is VBZ
the DT
car NN

This DT
is VBZ
the DT
dog NN

After writing this into a file

with open("new.txt","w") as wf:
     wf.write('\n'.join(' '.join(str(x) for x in tu) for tu in tag) )

The file I got something like this which not expected output.

('This', 'DT') ('is', 'VBZ') ('the', 'DT') ('house', 'NN')
('This', 'DT') ('is', 'VBZ') ('the', 'DT') ('car', 'NN')

How can I achieve the result mentioned above: sentences separated by '\n'(gap between columns(sentences)) and word's pos tag in corresponding second column. I searched a bit but no luck!. Kindly help please? :)

1 Answers

Use \n\n to get an empty line between array elements. Use \n for the items in an array and space ( ) for the tuples:

with open("new.txt", "w") as wf:
    wf.write('\n\n'.join('\n'.join(' '.join(x) for x in tu) for tu in tag))

If the expression becomes too complex, you can always go back to more step-by-step approach:

with open("new.txt", "w") as wf:
    for block in tag:            # outer array
        for line in block:       # inner array
            for word in line:    # tuples
                wf.write(word)
                wf.write(" ")
            wf.write("\n")
        wf.write("\n")

Yes, it has more lines, on the other hand side it's easier to debug and change.

Related