I'm trying to create a list in which each line of a file is its own list of the words in that line. So for example, if the file read:
apples oranges bananas
kale spinach
carrots tomatoes celery broccoli
Then I'd like the list to read:
l = [[["apples"], ["oranges"], ["bananas"]], [["kale"], ["spinach"]], [["carrots"], ["tomatoes"], ["celery"], ["broccoli"]]]
What's the best way to do this? readlines?
You may do like this..
with open(file) as f:
print [[[j] for j in i.split()] for i in f if i]
Example:
>>> s = '''apples oranges bananas
kale spinach
carrots tomatoes celery broccoli'''.splitlines()
>>> [[[j] for j in i.split()] for i in s if i]
[[['apples'], ['oranges'], ['bananas']], [['kale'], ['spinach']], [['carrots'], ['tomatoes'], ['celery'], ['broccoli']]]
You can do it, like this:
L = []
with open('words.txt','r') as f:
for line in f:
L.append(line.split())
As I tried to explain to @AvinashRaj, you'll need to use something like not i.isspace()
to filter out the empty lines (as they still contain a newline character)
with open(file) as fin:
print [[[j] for j in i.split()] for i in fin if not i.isspace()]
The with
block is called a context manager. It closes fin
once the end of the block is reached.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.