简体   繁体   中英

Nested lists for lines in text file? (Python 3)

I'm pretty new to coding in python and I'm trying to get my program to read in from a text file and create a list from the lines that looks like so:

[['This', 'is', 'an', 'example', 'sentence'], ['Another', 'sentence', 'to', 'explain', 'what', 'I', 'mean']]

That would come a text file like so:

This is an example sentence
Another sentence to explain what I mean

Basically each new line is a new nested list and each word is a new item. At the moment I've got this but it doesn't separate the words, despite me using the split function?

lines=[]
exampleFile = open('example.txt','rt')
for line in programFile:
    line.split()
    lines.append([line])
print(lines)

Thanks for any help :)

Here is the solution

lines=[]
exampleFile = open('example.txt','rt')
for line in exampleFile:
    line = line.split()
    lines.append(line)
print(lines)

as the people said above

lines.append(line) # you dont need []

if you use split function, you only can use it to a string

string1 = 'ab'
string2 = 'hello wrold'

string1.split() will give you

['ab']

string2.split() will give you

['hello', 'world']

您也可以在一行中完成此操作,而无需任何中间变量。

lines = [line.split() for line in open('example.txt')]

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM