【发布时间】:2017-08-29 17:48:56
【问题描述】:
我对 Python 很陌生,刚刚遇到了一个问题。
我尝试了许多建议的解决方案(主要来自this 问题),将 .txt 文档的每一行都转换为数组对象。我尝试只使用split()、split("\n") 和splitlines(),但它们都不起作用。文本文档中的每一行都是一个数字,它将对其进行一些计算。例如第一行是 50,但它对数字 5 进行第一次计算,对数字 0 进行第二次计算,然后在下一个一个它抛出一个关于无法将其转换为浮点数的错误(ValueError: could not convert string to float),可能是因为它试图转换 \n 或其他东西。
代码如下:
def weightTest(f, minWeight, fti):
weights = []
f_content = open(f, encoding='UTF-8')
for row in f_content:
length = row.splitlines()
for length in row:
weight = float(length) ** 3 * fti / 100 # ValueError
if weight < minWeight:
print("Smaller than the minimum weight.")
else:
print("The weight is " + str(weight) + " grams.")
weights.append(weight)
print("The biggest weight: " + str(max(weights)) + " kg")
f_content.close()
f = input("Insert file name: ")
alam = float(input("Insert minimum weight: "))
fti = float(input("Insert FTI: "))
weightTest(f, alam, fti)
这是使用的文本(不是空格,而是换行,StackOverflow 不想以某种方式显示它们): 50 70 75 55 54 80
这是日志:
Insert file name: kalakaalud.txt
Insert minimum weight: 50
Insert FTI: 0.19
Smaller than the minimum weight.
Smaller than the minimum weight.
Traceback (most recent call last):
File "C:\File\Location\kalakaal.py", line 18, in <module>
weightTest(f, minWeight, fti)
File "C:\File\Location\kalakaal.py", line 7, in weightTest
weight = float(length) ** 3 * fti / 100
ValueError: could not convert string to float:
【问题讨论】:
-
请发布您正在使用的数据示例。
标签: python arrays python-3.x split