我需要能够读取文件并将其导入 Python。导致问题的原因是文件不一致。这是文件里面的内容:
-0.2066687680781E-01 0.4329528510571E+00-0.9011796712875E+00
-0.4119676724076E-01 0.4006276726723E+00-0.9153143167496E+00
0.1022378727794E+00 0.2991854846478E+00-0.9487020373344E+00
0.2066854201257E-01 0.3005275726318E+00-0.9535492062569E+00
0.4130198806524E-01 0.3341401219368E+00-0.9416180849075E+00
0.6145291402936E-01 0.3000802397728E+00-0.9519324898720E+00
0.8211978524923E-01 0.3335199654102E+00-0.9391596317291E+00
0.6186530366540E-01 0.3671853244305E+00-0.9280881881714E+00
-0.2066862955689E-01 0.3678680062294E+00-0.9296482801437E+00
0.2066862955689E-01 0.3678680062294E+00-0.9296482801437E+00
0.0000000000000E+00 0.3344254791737E+00-0.9424222111702E+00
0.5163235664368E+00-0.3289847448468E-01-0.8557614684105E+00
0.5062980055809E+00-0.6575757265091E-01-0.8598478436470E+00
0.4863796830177E+00-0.3290597721934E-01-0.8731277585030E+00
0.4844416379929E+00-0.1312004029751E+00-0.8649293184280E+00
0.4652865529060E+00-0.9858986735344E-01-0.8796525001526E+00
0.4453650414944E+00-0.6581693142653E-01-0.8929267525673E+00
0.4761176705360E+00-0.6582681834698E-01-0.8769143819809E+00
大多数情况下,数字分为三列,但如果为负数,则没有空格,这会在将其加载到 Python 时导致错误。这是我用来加载文件的内容:
from numpy import *
import numpy as np
sphere = np.loadtxt("sphererad1.out")
这是我得到的错误:
File "<stdin>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/numpy/lib/npyio.py", line 827, in loadtxt
items = [conv(val) for (conv, val) in zip(converters, vals)]
ValueError: invalid literal for float(): 0.2899294197559E+00-0.1325698643923E+00
我无法重新生成数据,所以我必须弄清楚如何将其导入 Python。我尝试使用以下方法导入 Python:
opn = open("sphererad1.out")
sphere = opn.readlines()
opn.close()
为了测试将其分解为每个数字,我尝试了以下操作:
l = sphere[2000]
n = 18
[l[i:i+n] for i in range(0, len(l), n)]
我得到
[' -0.24', '73256886005E+00-0.', '6656686961651E-01-', '0.9666430950165E+0', '0\n']
如果第一个数字为负数,则左起 13 个空格;如果第一个数为正数,则左起 14 个空格。
n = 1
[l[i:i+n] for i in range(0, len(l), n)]
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '-', '0', '.', '2', '4', '7', '3', '2', '5', '6', '8', '8', '6', '0', '0', '5', 'E', '+', '0', '0', '-', '0', '.', '6', '6', '5', '6', '6', '8', '6', '9', '6', '1', '6', '5', '1', 'E', '-', '0', '1', '-', '0', '.', '9', '6', '6', '6', '4', '3', '0', '9', '5', '0', '1', '6', '5', 'E', '+', '0', '0', '\n']
如何让它忽略第一块空白,然后将其分解为三列数字并创建一个数组?