gpt4 book ai didi

python - 无法将字符串转换为浮点型

转载 作者:太空宇宙 更新时间:2023-11-03 15:59:04 25 4
gpt4 key购买 nike

我有一个 csv 文件,其中包含以下字符串形式的值:

'838.5',
'830.090027',
'820',
'827.559998',
'822.880005'

我正在阅读这样的文件:

file = []
for line in open('project.csv'):
our_data = line.split(",")

data.append(our_data)

我尝试通过以下方式将它们转换为 float :

data = [float(x) for x in file]

但是当我运行程序时出现此错误:

ValueError:无法将字符串转换为 float :。

如何在不编辑 csv 文件的情况下解决此问题?

最佳答案

剥猫皮的方法总是不止一种,但我会这样做:

# Read the entire contents of the file into a string (`numbers`).
# This includes newline characters and single-quotes.
with open('project.csv') as infile:
numbers = infile.read()

# Then remove the newline characters and single-quotes
# (replace each with the empty string, thus removing them)
# resulting in a string with numbers separated by commas
# e.g., `123.3,45.9,39.1`
numbers = numbers.replace("'","").replace("\n","")

# Then create a new list by splitting the string on comma
# and converting each individual item to a float
numbers = [float(num) for num in numbers.split(',')]

注释:

  • 如果文件确实很大,您可能需要逐行迭代而不是读取整个文件。

  • 如果输入文件可能包含格式错误,您必须更加小心以避免意外异常

关于python - 无法将字符串转换为浮点型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40515661/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com