我需要导入一个txt文件的数组值,但是当我打印看到我的值时,我得到这个错误:"无法将字符串转换为float:vector(0.1013,0.2395,1.1926),vector(0.1276) ,0.2361,1.1760),载体(0.13952644965926353,0.23617897201269641,1.1760001652770353),载体(0.16723382973344353,0.23617897201269641,1.176000165277035" 仅显示数组的几个值。 我知道我做错了什么,以及做正确的方法是什么?
def load_files(self):
dlg = wx.FileDialog(None,message="Choose File",wildcard= 'Points (*.txt; *.csv)|*.txt;*.csv', defaultFile="",style=wx.FD_OPEN|wx.FD_FILE_MUST_EXIST|wx.FD_CHANGE_DIR)
if dlg.ShowModal() == wx.ID_CANCEL:
print ('buh cancelaste')
else:
filename=dlg.GetFilename()
f = open(filename)
data = f.read()
data = np.array(data).astype(float)
print(data)
files = wx.Button(pan, label='Load Coordinates', pos=(x1+158,570), size = (150,40))
files.Bind(wx.EVT_BUTTON, load_files)
txt文件。
载体(0.1013,0.2395,1.1926),载体(0.1276,0.2361,1.1760),载体(0.13952644965926353,0.23617897201269641,1.1760001652770353),载体(0.16723382973344353,0.23617897201269641,1.1760001652770353),载体(0.18306661834726065,0.23617897201269641,1.1760001652770353),载体(载体(载体) 0.21077399842144068,0.23219954535704859,1.1760001652770353),载体(0.22264858988180353,0.22822011870140083,1.1760001652770353),载体(0.23452318134216635,0.22822011870140083,1.1760001652770353)
载体(-3.22925576,0.78085742,8.2709313),载体(0.12270437,0.29943441,1.65709467),载体(0.1278586,0.09019178,1.24548948),载体(0.25600214,-0.04258577,0.6109198)
载体(0.12795994,0.30532043,1.6896684),载体(0.13624277,0.09229906,1.24548948),载体(0.29656594,-0.08827312,0.69368916),载体(0.19870717,-0.09120946,1.19266453)
答案 0 :(得分:0)
错误消息表明传递给data
的{{1}}是表单中的一个或多个字符串
np.array
一根长串。你没有做任何事情来打破空格,逗号或换行。
使用vector(0.1013, 0.2395, 1.1926), vector(0.1276, 0.2361, 1.1760), vector(0.13952644965926353, 0.23617897201269641, 1.1760001652770353), vector(0.16723382973344353, 0.23617897201269641, 1.176000165277035
,您尝试将该字符串转换为浮点数或浮点数序列。 Python astype(float)
函数适用于float(astr)
之类的字符串,而不是具有多个数字的长字符串。即使你将"0.1013"
打成了像
data
它会有问题,因为vector(0.1013, 0.2395, 1.1926)
没有任何意义。
您需要对这些文件行进行更多解析。您需要将它们分成几行(例如vector
),剥离readline()
,将它们拆分为\n
之类的块,然后将其拆分为每个都有一个数字的字符串。换句话说,像这样的字符串列表将起作用:
vector()
观察当In [848]: np.array(['0.1013', '0.2395', '1.1926'])
Out[848]:
array(['0.1013', '0.2395', '1.1926'],
dtype='<U6')
In [849]: np.array(['0.1013', '0.2395', '1.1926']).astype(float)
Out[849]: array([ 0.1013, 0.2395, 1.1926])
是&#39; vector()&#39;字符串:
data
In [852]: np.array('vector(0.1013, 0.2395, 1.1926)')
Out[852]:
array('vector(0.1013, 0.2395, 1.1926)',
dtype='<U30')
In [853]: np.array('vector(0.1013, 0.2395, 1.1926)').astype(float)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-853-413e30b24430> in <module>()
----> 1 np.array('vector(0.1013, 0.2395, 1.1926)').astype(float)
ValueError: could not convert string to float: 'vector(0.1013, 0.2395, 1.1926)'
不会在字符串中搜索看起来像数字的子字符串。试试astype(float)
和变体。 float('123 45')
需要看起来像浮点数或整数的东西。