python-3.x - 在Python中将多个文本文件读取到二维numpy数组

标签 python-3.x

我有 10 个 txt 文件。每个都带有字符串。

A.txt: "This is a cat"
B.txt: "This is a dog"
.
.
J.txt: "This is an ant"

我想读取这些多个文件并将其放入二维数组中。

[['This', 'is', 'a', 'cat'],['This', 'is', 'a', 'dog']....['This', 'is', 'an', 'ant']]

from glob import glob
import numpy as np
for filename in glob('*.txt'):
    with open(filename) as f:
        data = np.genfromtxt(filename, dtype=str)

它没有按照我想要的方式工作。任何帮助将不胜感激。

最佳答案

您只是为每个文本文件生成不同的 numpy 数组,而不保存任何它们。像这样将每个文件添加到列表中并稍后转换为 numpy 怎么样?

data = []

for filename in glob('*.txt'):
    with open(filename) as f:
        data.append(f.read().split())

data = np.array(data)

关于python-3.x - 在Python中将多个文本文件读取到二维numpy数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55794954/

相关文章:

python - Python 3.8.5 cv2 -215:断言失败

python - 在 numpy 数组上应用统计方法 : unexpected results

python-3.x - 通过 pip : Unable to find vcvarsall. bat 安装flask-bcrypt

python - 如何为 SQLite 表名使用变量

python - 索引列表的文学方法,其中每个元素都有解释?

python - 将 gif 图像放入 tkinter 窗口

python - 我如何通过 pysftp 监视文件传输的进度

python - 读取 Fernet Key 导致 ValueError : Fernet key must be 32 url-safe base64-encoded bytes

python-3.x - Python/Pandas 返回找到的字符串的列和行索引

python - 将多个 Numpy 数组保存到一个 Numpy 二进制文件 (Python)