13

如果我有这样的文本文件:

Hello World
How are you?
Bye World

我如何将它读入这样的多维数组:

[["Hello", "World"],
 ["How", "are", "you?"],
 ["Bye" "World"]]

我努力了:

textFile = open("textFile.txt")
lines = textFile.readlines()
for line in lines:
    line = lines.split(" ")

但它只是返回:

["Hello World\n", "How are you?\n", "Bye World"]

如何将文件读入多维数组?

4

5 回答 5

17

使用列表推导和str.split

with open("textFile.txt") as textFile:
    lines = [line.split() for line in textFile]

演示:

>>> with open("textFile.txt") as textFile:
        lines = [line.split() for line in textFile]
...     
>>> lines
[['Hello', 'World'], ['How', 'are', 'you?'], ['Bye', 'World']]

with声明

with处理文件对象时最好使用关键字。这样做的好处是文件在其套件完成后正确关闭,即使在途中引发异常也是如此。它也比编写等效的 try-finally 块要短得多。

于 2013-09-27T16:52:50.957 回答
4

您可以使用mapunbound方法 str.split

>>> map(str.split, open('testFile.txt'))
[['Hello', 'World'], ['How', 'are', 'you?'], ['Bye', 'World']]

在 Python 3.x 中,您必须使用list(map(str.split, ...))来获取列表,因为map在 Python 3.x 中返回的是迭代器而不是列表。

于 2013-09-27T16:58:19.893 回答
1

添加到接受的答案:

with open("textFile.txt") as textFile:
    lines = [line.strip().split() for line in textFile]

如果将 '\n' 附加到每行的末尾,这将删除它。

于 2018-01-15T06:35:36.680 回答
0

也不要忘记使用strip删除\n

myArray = []
textFile = open("textFile.txt")
lines = textFile.readlines()
for line in lines:
    myArray.append(line.split(" "))
于 2013-09-27T16:54:54.770 回答
0

一个好的答案是:

def read_text(path):
    with open(path, 'r') as file:
        line_array = file.read().splitlines()
        cell_array = []
        for line in line_array:
            cell_array.append(line.split())
        print(cell_array)

它针对可读性进行了优化。

但是python语法让我们使用更少的代码:

def read_text(path):
    with open(path, 'r') as file:
        line_array = file.read().splitlines()
        cell_array = [line.split() for line in line_array]
        print(cell_array)

还有python让我们只用一行来做!

def read_text(path):
    print([[item for item in line.split()] for line in open(path)])
于 2018-04-06T16:44:10.447 回答