将字符串转换为浮点数时出现值错误

Value error when converting string to float

它显​​示将字符串转换为浮点数的值错误。 我的数据文件中的一行看起来像这样 100 1.2811559340137890E-003 我想也许 python 在转换时无法理解 E。以下是我的代码

import math
import matplotlib.pyplot as plt
x = []
y = []
f= open('C:/Users/Dell/assignment2/error_n.dat', 'r')
for line in f:
    line= line.split(' ')

    x.append(line[0])
    y.append(line[1])
for i in range(0,4):
    x[i]=float(x[i])
    x[i]=math.log(x[i])
    y[i]=float(y[i])
    y[i]=math.log(y[i])
        

plt.plot(y, x, marker = 'o', c = 'g')

plt.show()

字符串1.2811559340137890E-003可以毫无问题地转换为float。您可以在 Python shell:

中轻松尝试
>>> s = '1.2811559340137890E-003'
>>> float(s)
0.001281155934013789

但是,您实际上是在尝试转换一个空字符串。看看为什么:

>>> line = '100   1.2811559340137890E-003'
>>> line.split(' ')
['100', '', '', '1.2811559340137890E-003']

要解决您的问题,只需将 line.split(' ') 更改为 line.split():

>>> line.split()
['100', '1.2811559340137890E-003']

我认为问题在于,当您拆分该行时,第二项 (y) 是 ""(一个空字符串),这是无法转换为数字的一项。

float 能够处理科学记数法。但是根据您的描述,似乎 ValueError 是由于尝试将空字符串转换为浮点数而抛出的。

'100   1.2811559340137890E-003'.split(' ')

将return

['100', '', '', '1.2811559340137890E-003']

您可以在将字符串转换为浮点数之前检查字符串以处理此类错误。