Python 错误:无法将字符串转换为浮点
这是我的密码。我想从“data.txt”读取数据并将其转换为类型Python 错误:无法将字符串转换为浮点,python,type-conversion,Python,Type Conversion,这是我的密码。我想从“data.txt”读取数据并将其转换为类型float,但转换数据时出现问题。错误为“无法将字符串转换为浮点:” 该文件包含以逗号分隔的数字。我对文件类型感兴趣 lines.strip().split(",") 在我看来,strip()应该适用于字符串,但行应该是字符串列表。你可能需要双重理解,比如: [[float(x) for x in line.strip().split(",")] for line in lines] 没有你的数据,我无法证实这一点 您可以尝试移
float
,但转换数据时出现问题。错误为“无法将字符串转换为浮点:”
该文件包含以逗号分隔的数字。我对文件类型感兴趣
lines.strip().split(",")
在我看来,strip()应该适用于字符串,但行应该是字符串列表。你可能需要双重理解,比如:
[[float(x) for x in line.strip().split(",")] for line in lines]
没有你的数据,我无法证实这一点
您可以尝试移除浮动(x)并仅使用
nums= [x for x in lines.strip().split(",")]
print(nums)
要查看float(x)阻塞的确切值是多少。我唯一可以复制它的方法是在文件末尾有一个空行。因此,我的数据文件如下所示:
12.34 , 56.78 , 90.12 , 34.56
后面有一个空行,但我不能显示!这里是另一种格式:
od -xc data.txt
0000000 3231 332e 2034 202c 3635 372e 2038 202c
1 2 . 3 4 , 5 6 . 7 8 ,
0000020 3039 312e 2032 202c 3433 352e 0a36 000a
9 0 . 1 2 , 3 4 . 5 6 \n \n
0000037
请注意文件末尾附近的\n\n
请尝试以下代码:
def CrearMatriz():
archi = open("data.txt", "r")
num = archi.readlines()
for line in num:
line=line.strip()
if line:
nums=[float(x) for x in line.split(",")]
return nums
Numero = CrearMatriz()
但是,如果您有多行数字,则这不起作用!它将只返回最后一行数字。所以这可能更好(取决于您需要什么):
如果您想要列表列表,那么将
extend
更改为append
我并不是说这是一个完美的答案,但我建议您在列表理解之外进行解析,并在成功后将其附加到nums,至少在格式化修复所有问题之前
从我得到的错误来看,有一种可能是它看起来像行。strip()不能解释文件中的空行
def CrearMatriz():
archi = open("data.txt", "r")
num = archi.readlines()
for lines in num:
nums= [float(x) for x in lines.strip().split(",")]
return nums
def CrearMatriz2():
with open("data.txt", "r") as archi:
#having it in a separate function allows more robust formatting
#and error handling. append to nums on success
def tofloat(nums, x, lines, cntr):
try:
res = float(x)
assert isinstance(res, float)
nums.append(float(x))
except Exception, e:
msg = "exception %s on field:%s: for line #%s:%s:" % (e, x, cntr,lines)
print (msg)
return
nums = []
num = archi.readlines()
for cntr, lines in enumerate(num):
[tofloat(nums, x, lines, cntr) for x in lines.strip().split(",")]
return nums
data="""
0.12,30.2,30.5,22
3,abc,4
"""
with open("data.txt","w") as f_test:
f_test.write(data)
try:
print "\n\ncalling CrearMatriz"
Numero = CrearMatriz()
print "\nCrearMatriz()=>", Numero
except Exception, e:
print e
try:
print "\n\ncalling CrearMatriz2"
Numero = CrearMatriz2()
print "\nCrearMatriz2()=>", Numero
except Exception, e:
print e
这给了
calling CrearMatriz
could not convert string to float:
calling CrearMatriz2
exception could not convert string to float: on field:: for line #0:
:
exception could not convert string to float: abc on field:abc: for line #2:3,abc,4
:
exception could not convert string to float: on field:: for line #3:
:
CrearMatriz2()=> [0.12, 30.2, 30.5, 22.0, 3.0, 4.0]
您能告诉我们
data.txt
中的数据是如何组织的吗?例如,粘贴前5行或其他内容。在系统上尝试:float('Luis')
,float('')
,float('\n')
,您将understand@GrijeshChauhan,但根据OP的说法,他的档案中没有这些东西。它只包含数字和逗号。甚至换行符也会被strip()
@Kevin删除:换行符会被readlines()
删除,所以当它到达strip()
@TigerhawkT3时,没有任何换行符可以删除-换行符不会被readlines
删除。这是一个调试建议,而不是一个答案。在问题中,num
是字符串的列表
,行
是字符串。不是很好的变量名,但你已经有了。这可以通过在文件对象上迭代列表理解来完成,同时使用with是打开文件的更好方法。@PadraicCunningham:是的,但我希望尽可能保留原始代码,以便OP可以看到更改。如果你试图做太多的改变,那么对没有经验的人来说,这可能只是白噪音。我的理念是在单个答案中尽可能少地更改。我认为养成与文件一起使用或至少关闭文件的习惯很重要。如果您尝试在循环中写入文件,然后在关闭之前打开文件以读取内容,您将看到一个问题,还有很多时候,结案会引起问题,但正如你所说,现在不是时间和地点。我们在阅读,而不是写作。对于,文件对象在退出时关闭,即使出现错误(测试它)。无论如何,我认为回答这个人的问题更重要。
def CrearMatriz():
archi = open("data.txt", "r")
num = archi.readlines()
for lines in num:
nums= [float(x) for x in lines.strip().split(",")]
return nums
def CrearMatriz2():
with open("data.txt", "r") as archi:
#having it in a separate function allows more robust formatting
#and error handling. append to nums on success
def tofloat(nums, x, lines, cntr):
try:
res = float(x)
assert isinstance(res, float)
nums.append(float(x))
except Exception, e:
msg = "exception %s on field:%s: for line #%s:%s:" % (e, x, cntr,lines)
print (msg)
return
nums = []
num = archi.readlines()
for cntr, lines in enumerate(num):
[tofloat(nums, x, lines, cntr) for x in lines.strip().split(",")]
return nums
data="""
0.12,30.2,30.5,22
3,abc,4
"""
with open("data.txt","w") as f_test:
f_test.write(data)
try:
print "\n\ncalling CrearMatriz"
Numero = CrearMatriz()
print "\nCrearMatriz()=>", Numero
except Exception, e:
print e
try:
print "\n\ncalling CrearMatriz2"
Numero = CrearMatriz2()
print "\nCrearMatriz2()=>", Numero
except Exception, e:
print e
calling CrearMatriz
could not convert string to float:
calling CrearMatriz2
exception could not convert string to float: on field:: for line #0:
:
exception could not convert string to float: abc on field:abc: for line #2:3,abc,4
:
exception could not convert string to float: on field:: for line #3:
:
CrearMatriz2()=> [0.12, 30.2, 30.5, 22.0, 3.0, 4.0]