read file into list of lists

bockman at virgilio.it bockman at virgilio.it
Fri Jul 11 09:29:13 EDT 2008


On 11 Lug, 15:15, antar2 <desoth... at yahoo.com> wrote:
> Hello,
>
> I can not find out how to read a file into a list of lists. I know how
> to split a text into a list
>
> sentences = line.split(\n)
>
> following text for example should be considered as a list of lists (3
> columns and 3 rows), so that when I make the print statement list[0]
> [0], that the word pear appears
>
> pear noun singular
> books nouns plural
> table noun singular
>
> Can someone help me?
>
> Thanks


You can use split again, using ' ' or nothing(defaults to whitespace
characters) as separator,
like this:

>>> text = """pear noun singular
books nouns plural
table noun singular"""

>>> words = [ x.split() for x in text.split('\n') ]
>>> print words
[['pear', 'noun', 'singular', ''], ['books', 'nouns', 'plural', ''],
['table', 'noun', 'singular']]


Ciao
-----
FB



More information about the Python-list mailing list