Python ValueError:无法将字符串转换为浮点数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19081239/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 12:47:59  来源:igfitidea点击:

ValueError: could not convert string to float

python

提问by user2828933

I have:

我有:

data1=open('file1.txt','r')
data2=open('file2.txt','w+')

for line in data1.readlines():
    items = line.split(' ')
    x = log(float(items[0]))
    y = float(items[1])
    data2.write(x)
    data2.write('\t')
    data2.write(y)
    data2.write('\n')

where file1 contains

其中 file1 包含

l   0.1
2   0.1
3   0.1
4   0.1
5   0.1
6   0.1
7   0.1
8   0.1
9   0.1
10  0.1

Getting

得到

ValueError: could not convert string to float: 1

I dont quite understand why im getting an error, please help me. Thanks in advance.

我不太明白为什么我收到错误,请帮助我。提前致谢。

采纳答案by jabaldonedo

That is because the first line of your file is letter lwhich cannot be converted to a float number. Maybe it is a typo and you want it to be number 1? if so, then your code will be correct. Then you need other changes in order to make your code more pythonic like using withfor dealing with files:

那是因为文件的第一行是l无法转换为浮点数的字母。也许这是一个错字,您希望它是数字1?如果是这样,那么您的代码将是正确的。然后您需要其他更改,以使您的代码更像with用于处理文件的Pythonic :

from math import log
txt = list()
with open('file1.txt', 'r') as fr, open('file2.txt', "w+") as fw:
    for line in fr:
        items = line.split()
        txt.append("{0}\t{1}".format(items[0], log(float(items[1]))))
    fw.write("\n".join(txt))

回答by Erik Kaplun

What jabaldonedo said, + split(' ')splits most of your lines into a list of several items, not just 2, because each line contains multiple spaces not just one.

jabaldonedo 所说的, +split(' ')将您的大部分行拆分为多个项目的列表,而不仅仅是 2 个,因为每行包含多个空格而不仅仅是一个。

For example:

例如:

>>> '2   0.1'.split(' ')
['2', '', '', '0.1']

so items[1]will definitely not give you what you need.

所以items[1]绝对不会给你你需要的。

A quick solution would be to simply take the last element of itemsby doing items[-1]. But best do the splitting properly (i.e. using regular expressions):

一个快速的解决方案是简单地items通过执行items[-1]. 但最好正确进行拆分(即使用正则表达式):

>>> import re
>>> re.split(' +', '2   0.1'.split(' '))
['2', '0.1']

Or, if you'd rather not use regular expressions, another slightly inelegante workaround would be:

或者,如果您不想使用正则表达式,另一种稍微不雅的解决方法是:

>>> items = '2   0.1'.split(' ')
>>> items = [x for x in items if x]
>>> items
['2', '0.1']

NOTE:I'm using interactive Python, in case you were wondering about the >>>prefixes.

注意:我正在使用交互式 Python,以防您对>>>前缀感到疑惑。

UPDATE:'2 0.1'.split()(i.e. split()without argument) seems to do exactly the same job; i.e. it gets rid of the multiple spaces, so to say. (thanks, @hcwhsa).

更新:('2 0.1'.split()split()没有参数)似乎做完全相同的工作;即它摆脱了多个空格,可以这么说。(谢谢,@hcwhsa)。