473,399 Members | 4,177 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,399 software developers and data experts.

read file into list of lists

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
Jul 11 '08 #1
7 9079
Hello,

A way to do it

================================================== =============
from __future__ import with_statement

res = []
with open("sentences.txt","r") as f:
sentences = [elem for elem in f.read().split('\n') if elem]
for sentence in sentences:
res.append(sentence.split())

print res
================================================== =============

antar2 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
Jul 11 '08 #2
On 11 Lug, 15:15, antar2 <desoth...@yahoo.comwrote:
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
Jul 11 '08 #3
On Jul 11, 2:15 pm, antar2 <desoth...@yahoo.comwrote:
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
lofl = [line.strip().split() for line in the_opened_file]

- Paddy.
Jul 11 '08 #4
antar2 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?

class Table(object):

def __init__(self, text=None):
self.rows = []
if text:
self.write(text)

def write(self, text):
self.rows.extend(line.split() for line in text.splitlines())

def read(self):
return '\n'.join(' '.join(row) for row in self.rows)

def __getitem__(self, i):
return self.rows[i]

def __iter__(self):
return iter(self.rows)

table = Table()

table.write('apple orange coconut')

print table[0][1]

print table.read()

table.write('clematis rose lily')

print table[1][2]

print table.read()
for row in table:
print row

(If you have quoted items, it is more difficult)

G.

Jul 11 '08 #5
Laurent Rahuel wrote that antar2 wrote:
>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
File objects are themselves iterable, returning one line per iteration. So a
simple approach is:
>>table = [line.split() for line in open('sentences.txt')]
table[0][0]
'pear'
Jeffrey

Jul 11 '08 #6
On Jul 11, 11:35 pm, Paddy <paddy3...@googlemail.comwrote:
On Jul 11, 2:15 pm, antar2 <desoth...@yahoo.comwrote:
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

lofl = [line.strip().split() for line in the_opened_file]
>>line = ' foo bar '
line.strip().split()
['foo', 'bar']
>>line.split()
['foo', 'bar']

Jul 11 '08 #7
On Jul 11, 9:32*pm, John Machin <sjmac...@lexicon.netwrote:
On Jul 11, 11:35 pm, Paddy <paddy3...@googlemail.comwrote:
On Jul 11, 2:15 pm, antar2 <desoth...@yahoo.comwrote:
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
lofl = [line.strip().split() for line in the_opened_file]
>line = ' * foo * bar * '
line.strip().split()
['foo', 'bar']
>line.split()

['foo', 'bar']
Thanks , ta.

- Paddy.
Jul 12 '08 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: JDJones | last post by:
I'm trying to write a script that will read from a text list of songs that I burned onto my CD (Albums011.txt), then write to the database text the new text made ready for inserting into a...
0
by: Majordomo | last post by:
-- >>>> --36742377 **** Command '--36742377' not recognized. >>>> Content-Type: text/plain; charset=us-ascii **** Command 'content-type:' not recognized. >>>> Content-Transfer-Encoding: 7bit...
0
by: Taylor Lewick | last post by:
I have a large SQL file that contains a bunch of create table statements.= ... How do I get mysql to read in this file and process the sql. =20 I am not thinking load data infile because it...
0
by: Bennett Haselton | last post by:
I'm trying to port my MySQL tables for a database called "tracerlock" from one server to another. On the old server, in the /var/lib/mysql/tracerlock directory, there was a ".MYD", ".MYI" and...
2
by: Sandman | last post by:
Just looking for suggestion on how to do this in my Web application. The goal is to keep track of what a user has and hasn't read and present him or her with new material I am currently doing...
165
by: Dieter | last post by:
Hi. In the snippet of code below, I'm trying to understand why when the struct dirent ** namelist is declared with "file" scope, I don't have a problem freeing the allocated memory. But...
1
by: irfath | last post by:
Write an interactive program that reads three (3) lists of numbers, which are stored in three separate files, and creates one (1) sorted list. Each file should contain not more than 15 numbers....
6
by: Dag | last post by:
I have an application which works with lists of tuples of the form (id_nr,'text','more text',1 or 0). I'll have maybe 20-50 or so of these lists containing anywhere from 3 to over 30000 tuples. ...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.