简体   繁体   English

读取文本文件并将字符串转换为浮点数

[英]Reading a text file and converting string to float

I have a text file called "foo.txt", with a list of numbers, one on each line, for example:我有一个名为“foo.txt”的文本文件,其中包含一个数字列表,每行一个,例如:

0.094195
0.216867
0.326396
0.525739
0.592552
0.600219
0.637459
0.642935
0.662651
0.657174
0.683461

I now want to read these numbers into a Python list.我现在想将这些数字读入 Python 列表。 My code to do this is as follows:我的代码如下:

x = []
file_in = open('foo.dat', 'r')
for y in file_in.read().split('\n'):
    x.append(float(y))

But this gives me the error:但这给了我错误:

ValueError: could not convert string to float

What am I doing wrong?我做错了什么?

Edit :编辑

commented by martineau : you can also use if y: to eliminate None or empty string. martineau评论:您还可以使用if y:来消除None或空字符串。

Original Answer:原答案:

It fails due to you are using newline character as a separator, therefore the last element is empty string由于您使用换行符作为分隔符而失败,因此最后一个元素是空字符串

you can add y.isdigit() to check whether y is numeric.您可以添加y.isdigit()来检查 y 是否为数字。

x = []
file_in = open('sample.csv', 'r')
for y in file_in.read().split('\n'):
    if y.isdigit():
        x.append(float(y))

OR

you can change read().split("\\n") to readlines()您可以将read().split("\\n")更改为readlines()

OR

remove the leading/trailing characters from y.从 y 中删除前导/尾随字符。 it handles the lines with extra whitespaces它处理带有额外空格的行

for y in file_in:
    trimed_line = y.strip()  # leading or trailing characters are removed

How about this approach:这种方法怎么样:

x = []
with open('foo.dat', 'r') as f:
    for line in f:
        if line: #avoid blank lines
            x.append(float(line.strip()))

Or:或者:

with open('foo.dat', 'r') as f:
    lines = (line.strip() for line in f if line)
    x = [float(line) for line in lines]

Finally more compact:最后更紧凑:

with open('foo.dat', 'r') as f:
    x = [float(line.strip()) for line in lines if line]

This way you don't have to worry about blank lines and you make proper conversion from string to float这样您就不必担心空行,并且可以正确地从string转换为float

Usually files has empty line at the end so probably you're trying to cast empty string to float.通常文件末尾有空行,因此您可能正在尝试将空字符串转换为浮动。

Instead of file_in.read().split('\\n') you could use:您可以使用代替file_in.read().split('\\n')

for line in file_in.readlines():
  x.append(float(line))

Method readlines returns list of all lines from given file and skips last empty line if present.方法readlines返回给定文件中所有行的列表,如果存在则跳过最后一个空行。

You can try using the default float function您可以尝试使用默认的浮动功能

>>> float("1.1")
1.1

You could also try using the python try else statement which will run the code until it catches a error and runs a else statement.您还可以尝试使用 python try else 语句,该语句将运行代码,直到它捕获错误并运行 else 语句。

try:
   try_this(whatever that might bring up a error)
except SomeException as exception:
   #Handle exception
else:
   return something

There might be a possibility that there is a blank line end of the file which might create errors.文件末尾可能有一个空行,这可能会产生错误。 Try using the try else statement because of it.尝试使用 try else 语句,因为它。

I think You string like this : '0.1111, 0.1111' or other我认为你的字符串是这样的:'0.1111, 0.1111' 或其他

file_in = open('foo.dat', 'r')
for y in file_in.readlines()[0]:
    x.append(float(y))

You can use a function to decide whether the string you're parsing is a number or not.您可以使用函数来确定您解析的字符串是否为数字。 Based on this question 1 you can do that this way:基于这个问题1你可以这样做:

def is_number(s):
    try:
        float(s)
        return True
    except ValueError:
        return False

x = []
file_in = open('filename.dat', 'r')
for y in file_in.read().split('\n'):
    if is_number(y):
        x.append(float(y))
file_in.close()

You can use this way你可以用这种方式

Note : reedline() is a string, reedlines() is a list注意:reedline() 是一个字符串,reedlines() 是一个列表

file_in = open('foo.dat', "r")
r  =  file_in.readlines()
file_in.close()
l = 0
x = []
while l < len(r) :
    floating = float(r[l])
    x.append(floating)
    l += 1

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

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