我有一个格式低于
的文本文件id x, y
0[0.0, 1.0]
1[0.0, 2.0]
2[0.1, 2.5]
:
:
我需要加载此文本文件。我试过了:
numpy.genfromtxt('FileName', delimiter=",", names=True)
但是[
的存在阻止了它读取文件。我该怎么办?
答案 0 :(得分:3)
在将文件提供给genfromtxt()
之前,您需要将文件转换为NumPy期望的格式。幸运的是,你可以用Python本身做到这一点。
f1 = open("file.txt", "rU")
f2 = open("output.txt", "wt")
for line in f1:
line = line.replace("[", ",")
line = line.replace("]", "")
f2.write(line)
f2.close()
f1.close()
希望这有帮助。
答案 1 :(得分:1)
'试试这个
import numpy as np
X=[] # keep x, y
id=[] # keep ids
file_toload=open('FileName',"r") # start reading a file
file_toload.readline()# get rid of headers
for line in file_toload: # loop through all remaining lines
line =line.replace("[",",") # replace [ with comma first row becomes '0,0.0, 1.0]'
line =line.replace("]","") # replace ] with empty string first row becomes '0,0.0, 1.0'
line =line.replace(" ","") # replace white space with empty string first row becomes '0,0.0,1.0'
line =line.replace("\n","") # replace break line with empty string , just in case there is one
line =line.replace("\r","") # replace car. return with empty string , just in case there is one
splits= line.split(",") # split by comma first row becomes ['0','0.0','1.0']
id.append(float(splits[0])) # append id , contains [0.0] , you could use int() instead of float()
X.append([float(splits[1]),float(splits[2])]) # append x,y , [[0.0,1.0]]
file_toload.close() # close the file
X=np.array(X) # convert X to numpy
id=np.array(id) # convert id to numpy
##### print shapes of the arrays #####
print (X.shape)
print (id.shape)