简体   繁体   English

使用python从文件中读取浮点数

[英]Reading floats from file with python

My input file has the form: 我的输入文件有以下形式:

5.0, 1000.0, 100000000000000.0, 115.2712, 230.538, 345.796, 461.0408, 
1.053E-09, 1.839E-09, 1.632E-10, 1.959E-12, 4.109, 3.683, 3.586, 3.650 

where every number is essentially in a line. 每个数字基本上都在一条线上。

What I want to do is read all the floats, and then append only columns 7 through 10 to an array. 我想要做的是读取所有浮点数,然后仅将第7列到第10列附加到数组中。

Here's what I've written: 这是我写的:

T=[]
with open("test.txt", "r") as file1:
    for line in file1.readlines():
        f_list = [float(i) for i in line.split(",")]
        T.append(float(f_list[7]))
        T.append(float(f_list[8]))
        T.append(float(f_list[9]))
        T.append(float(f_list[10]))

When I run the above I get: 当我运行以上内容时,我得到:

ValueError: could not convert string to float:

I think there's something wrong with the float(i) part, but I can't find a way around it. 我认为float(i)部分有问题,但我无法找到解决方法。

I've seen people having similar problems here, but none of the fixes I've tried so far have helped. 我看到人们在这里遇到类似的问题,但到目前为止我所尝试过的修复都没有帮助。 Any help is greatly appreciated. 任何帮助是极大的赞赏。

No the problem is that your first line ends with a comma : 没问题是你的第一行以逗号结尾

5.0, 1000.0, 100000000000000.0, 115.2712, 230.538, 345.796, 461.0408,
1.053E-09, 1.839E-09, 1.632E-10, 1.959E-12, 4.109, 3.683, 3.586, 3.650 

As a result, you want to process a string that only contains spaces (like ' ' ). 因此,您希望处理仅包含空格的字符串(例如' ' )。 And float(' ') fails since it is not a number (it actually reports this): 并且float(' ')失败,因为它不是一个数字(它实际上报告了这个):

>>> float(' ')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: 
>>> float('a')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: 'a'

But a space simply is invisible when printed. 但是印刷时空间简直是看不见的。

You can solve it by adding a filter statement to the list comprehension: 您可以通过向列表推导添加过滤器语句来解决此问题:

T = []
with open("test.txt", "r") as file1:
    for line in file1.readlines():
        f_list = [float(i) for i in line.split(",") if i.strip()]
        T += f_list[7:11]

Furthermore this will not work since none of the lines has 7-11 floats. 此外,这将无法工作,因为没有一行的有7-11浮动。 So you will never add these floats anyway. 所以你永远不会添加这些花车。

You can however use the following code: 但是,您可以使用以下代码:

with open("test.txt", "r") as file1:
    f_list = [float(i) for line in file1 for i in line.split(',') if i.strip()]
    T = f_list[7:11]

This will result in T being equal to: 这将导致T等于:

>>> T
[1.053e-09, 1.839e-09, 1.632e-10, 1.959e-12]

Your problem is that when you split line , the resulting list most likely contains whitespace. 您的问题是,当您拆分line ,结果列表很可能包含空格。 This would cause float() to fail. 这会导致float()失败。 You need to sanitize your split list first by testing if an element is actually a valid float number. 您需要首先通过测试元素是否实际是有效的浮点数来清理拆分列表。 eg: 例如:

>>> def is_float(n):
    try:
        float(n)
        return True
    except:
        return False


>>> 
>>> line = '5.0, 1000.0, 100000000000000.0, 115.2712, 230.538, 345.796, 461.0408,'
>>> lst = [float(n) for n in line.split(',') if is_float(n)]
>>> lst
[5.0, 1000.0, 100000000000000.0, 115.2712, 230.538, 345.796, 461.0408]
>>>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM