我有一个数据集,我将从文本文件中读取:
0.0000000e+000 -1.4275799e-003
2.0000000e-002 -1.1012760e-002
4.0000000e-002 -1.0298970e-002
6.0000000e-002 -8.9733599e-003
8.0000000e-002 -9.6871497e-003
1.0000000e-001 -1.2236400e-002
1.2000000e-001 -1.4479739e-002
1.4000000e-001 -1.3052160e-002
1.6000000e-001 -1.1216700e-002
1.8000000e-001 -8.6674497e-003
2.0000000e-001 -8.6674497e-003
2.2000000e-001 -1.3358070e-002
2.4000000e-001 -1.7946720e-002
2.6000000e-001 -1.9782179e-002
我希望在将文本文件读取为以下格式后进行转换:
(0.0000000e+000, -1.4275799e-003), (2.0000000e-002, -1.1012760e-002), (4.0000000e-002, -1.0298970e-002), ..., (2.6000000e-001, -1.9782179e-002)
应该排成一行。
有人可以帮我这个吗?我的代码如下:
with open('1.txt') as f:
for line in f:
n0 = map(float, line.split())
n1 = tuple(n0)
n2 = zip(n1)
print n0
我没有收到任何错误,但问题是zip
命令没有在行中提供所需的格式。
答案 0 :(得分:0)
with open("1.txt" , "rb") as txtfile:
outputstr = ""
ioreader = txtfile.read()
for line in ioreader.split("\n"):
outputstr += str(tuple(line.split("\t")))
outputstr += ","
print outputstr
答案 1 :(得分:0)
下面的代码应该完成工作:
def load_data(fn):
with open(fn) as f:
lines = f.readlines()
return [tuple(map(float, x)) for x in [row.split() for row in lines]]
def display_data(lst):
return lst.__repr__()[1:-1]
ppp = load_data('1.txt')
print display_data(ppp)
#(0.0, -0.0014275799), (0.02, -0.01101276), (0.04, -0.01029897), (0.06, -0.0089733599), (0.08, -0.0096871497), (0.1, -0.0122364), (0.12, -0.014479739), (0.14, -0.01305216), (0.16, -0.0112167), (0.18, -0.0086674497), (0.2, -0.0086674497), (0.22, -0.01335807), (0.24, -0.01794672), (0.26, -0.019782179)
print ppp
#[(0.0, -0.0014275799),
# (0.02, -0.01101276),
# (0.04, -0.01029897),
# (0.06, -0.0089733599),
# (0.08, -0.0096871497),
# (0.1, -0.0122364),
# (0.12, -0.014479739),
# (0.14, -0.01305216),
# (0.16, -0.0112167),
# (0.18, -0.0086674497),
# (0.2, -0.0086674497),
# (0.22, -0.01335807),
# (0.24, -0.01794672),
# (0.26, -0.019782179)]