-1

我有一个看起来像这样的文本文件:

[142, 5068, 3648, 6454, 5895, 4669, ..., 1626, 5665]
[280, 1076, 3509, 2713, 2176, 3764, ..., 4655, 3120]
[280, 6322, 5545, 101, 3218, 5308, ..., 3431, 4535]
[142, 5415, 164, 8507, 985, 8545, 2619, ..., 5757, 1538]
[71, 554, 4525, 94, 940, 4794, 1631, 1310, ..., 5474, 8179]
[71, 5639, 8195, 5706, 8300, 8206, 3268]
[142, 5068, 3648, 6454, 5895, 4669, 1071, ..., 4703, 6007, 2139, 6967, 3507, 7573, 1848, 1626, 5665]
[280, 1076, 3509, 2713, 2176, 3764, 2265, ..., 4655, 3120]

我想将它们作为数组的数组读入 NumPy,如下所示:

routes = [
[142, 5068, 3648, 6454, 5895, 4669, ..., 1626, 5665],
[280, 1076, 3509, 2713, 2176, 3764, ..., 4655, 3120],
[280, 6322, 5545, 101, 3218, 5308, ..., 3431, 4535],
[142, 5415, 164, 8507, 985, 8545, 2619, ..., 5757, 1538],
[71, 554, 4525, 94, 940, 4794, 1631, 1310, ..., 5474, 8179],
[71, 5639, 8195, 5706, 8300, 8206, 3268],
[142, 5068, 3648, 6454, 5895, 4669, 1071, ..., 4703, 6007, 2139, 6967, 3507, 7573, 1848, 1626, 5665],
[280, 1076, 3509, 2713, 2176, 3764, 2265, ..., 4655, 3120]
]

最pythonic的方法是什么?

4

3 回答 3

1

该文件似乎是一个 python 数据结构,因此您可以使用该ast模块转换每一行:

import ast
import numpy as np

with open('file.txt', 'r') as f:
   a = np.array([ast.literal_eval(line) for line in f])
于 2021-04-18T01:56:57.463 回答
1

这是一种方法:

routes = np.loadtxt('route.txt', delimiter=',', dtype=int,
                     converters={0: lambda s: s[1:], -1: lambda s: s[:-1]})
于 2021-04-18T01:52:43.780 回答
0

您最简单的选择就是单独转换每一行。Strip 会去掉每行开头和结尾的字符。

text_file = open("route.txt", "r")

# List of strings for each line
lines = text_file.readlines()
route = None
for i in range(len(lines)):
    # Gets rid of brackets and newline and converts to numpy array
    arr = np.fromstring(lines[0].strip('[]\n'), dtype=int, sep=',')
    # This just instantiates the array with the correct shape as soon as its known
    if i == 0:
        route = np.zeros((len(lines), len(arr)))
    route[i] = arr
    
print(route)
于 2021-04-18T01:47:18.947 回答