Python 读取文本文件并将字符串转换为浮点数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36343646/
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
Reading a text file and converting string to float
提问by Karnivaurus
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. My code to do this is as follows:
我现在想将这些数字读入 Python 列表。我的代码如下:
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?
我究竟做错了什么?
回答by Haifeng Zhang
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. it handles the lines with extra whitespaces
从 y 中删除前导/尾随字符。它处理带有额外空格的行
for y in file_in:
trimed_line = y.strip() # leading or trailing characters are removed
回答by Iron Fist
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
回答by maxadorable
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 语句,因为它。
回答by ?ukasz Lalik
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
返回给定文件中所有行的列表,如果存在则跳过最后一个空行。
回答by ?ukasz Lalik
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))
回答by Moe
You can use a function to decide whether the string you're parsing is a number or not. Based on this question 1you can do that this way:
您可以使用函数来确定您解析的字符串是否为数字。基于这个问题1你可以这样做:
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
x = []
file_in = open('foo.dat', 'r')
for y in file_in.read().split('\n'):
if is_number(y):
x.append(float(y))
回答by abu8na9
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