我想使用Python将此文本文件拆分为3个(称为x
,y
和e
)列表,我似乎无法做到这一点。
这就是文本文件(称为数据)的样子:
x y e
-2 2.1 0.170358869161
0 2.4 0.170202773308
2 2.5 -0.138557648063
4 3.5 0.187965696415
6 4.2 -0.473073365465
这是我到目前为止无法运行的代码:
x=[]
y=[]
e=[]
try:
data = open('data.txt', 'rt')
except:
sys.exit('cannot find file')
with data:
try:
x.append(data[:1])
y.append(data[2:3])
e.append(data[4:5])
except:
sys.exit('cannot create lists')
答案 0 :(得分:3)
这样做:
with data as f: # f is the file object
for line in f: # you can iterate over a file object line-by-line
xi, yi, ei = line.split()
x.append(xi)
y.append(yi)
e.append(ei.strip()) # ei will have a \n on the end
如果你对形状的假设是正确的,你可以在追加它们时将它们强制为整数或浮点数。
如果您有熊猫,我建议read_csv
:
>>> import pandas as pd
>>> pd.read_csv('data.txt', delim_whitespace=True)
x y e
0 -2 2.1 0.170359
1 0 2.4 0.170203
2 2 2.5 -0.138558
3 4 3.5 0.187966
4 6 4.2 -0.473073
答案 1 :(得分:0)
您可以使用csv lib:
import csv
x, y, e = [], [], []
with open("in.csv") as f:
next(f)
for a, b, c in csv.reader(f, delimiter=" ", skipinitialspace=1):
x.append(float(a))
y.append(float(b))
e.append(float(c))
输出:
[-2.0, 0.0, 2.0, 4.0, 6.0]
[2.1, 2.4, 2.5, 3.5, 4.2]
[0.170358869161, 0.170202773308, -0.138557648063, 0.187965696415, -0.473073365465]
或使用defaultdict对元素进行分组:
import csv
from collections import defaultdict
with open("in.csv") as f:
d = defaultdict(list)
for dct in csv.DictReader(f, delimiter=" ", skipinitialspace=1):
for k, v in dct.items():
d[k].append(float(v))
from pprint import pprint as pp
pp(dict(d))
输出:
{'e': [0.170358869161,
0.170202773308,
-0.138557648063,
0.187965696415,
-0.473073365465],
'x': [-2.0, 0.0, 2.0, 4.0, 6.0],
'y': [2.1, 2.4, 2.5, 3.5, 4.2]}