无法将文本文件读入2D数组

时间:2018-04-22 22:41:17

标签: python arrays python-3.x

我试图通过Python将文本文件读入2D数组。 文本文件如下:

7ee0c0d15fe800000f80202278e0c0f1
00007ee0c0d15fc000000f802022c0f1

我需要2D数组格式,如:

[[[7],[e],[e],[0],[c],[0],[d],[1],[5],[f],[e],[8],[0],[0],[0],[0],[0],[f],[8],[0],[2],[0],[2],[2],[7],[8],[e],[0],[c],[0],[f],[1]],
[[0],[0],[0],[0],[7],[e],[e],[0],[c],[0],[d],[1],[5],[f],[c],[0],[0],[0],[0],[0],[0],[f],[8],[0],[2],[0],[2],[2],[c],[0],[f],[1]]]

元素是十六进制数。

3 个答案:

答案 0 :(得分:4)

html-webpack-plugin

答案 1 :(得分:3)

创建文件:

data = """7ee0c0d15fe800000f80202278e0c0f1
00007ee0c0d15fc000000f802022c0f1"""
fn = "someFile.txt"
with open(fn,"w") as f:
    f.write(data)

读取文件:

fn = "someFile.txt"
k = []
with open(fn,"r") as f:
    for line in f:
      k.append(list(line.rstrip("\n"))) # convert each line into list, strip \n

print(k) # these are all strings

# convert to decimal
d = [ [int('0x'+i,16) for i in x] for x in k]

print(d) # converted to int

输出:

[['7', 'e', 'e', '0', 'c', '0', 'd', '1', '5', 'f', 'e', '8', 
  '0', '0', '0', '0', '0', 'f', '8', '0', '2', '0', '2', '2', 
  '7', '8', 'e', '0', 'c', '0', 'f', '1'], 
 ['0', '0', '0', '0', '7', 'e', 'e', '0', 'c', '0', 'd', '1', 
  '5', 'f', 'c', '0', '0', '0', '0', '0', '0', 'f', '8', '0', 
  '2', '0', '2', '2', 'c', '0', 'f', '1']]

[[7, 14, 14, 0, 12, 0, 13, 1, 5, 15, 14, 8, 0, 0, 0, 0, 0, 15,
  8, 0, 2, 0, 2, 2, 7, 8, 14, 0, 12, 0, 15, 1], 
 [0, 0, 0, 0, 7, 14, 14, 0, 12, 0, 13, 1, 5, 15, 12, 0, 0, 0, 
  0, 0, 0, 15, 8, 0, 2, 0, 2, 2, 12, 0, 15, 1]]

答案 2 :(得分:2)

这只是为了有一个想法

import numpy as np
x,y = np.genfromtxt('data.txt',dtype='str', usecols=(0,1), unpack=True)
x_letter = []
y_letter = []
letter = [x_letter]

for letter in x:
    letters = [letter] 
    x_letter.append(letters)

for letter in y:
    letters = [letter] 
    y_letter.append(letters)

final = [x_letter,y_letter]
print (final)
相关问题