无法将多行字符串拆分为行数组

时间:2017-04-04 13:30:56

标签: python arrays python-3.x split

我是Python的新手,遇到了一个问题。

我尝试了许多解决方案(主要来自this问题),将.txt文档的每一行都放到数组对象中。我尝试仅使用split()split("\n")splitlines(),但它们都不起作用。文本文档中的每一行都是一个数字,它将对其进行一些计算。例如,第一行是 50 ,但它首先计算数字 5 ,第二行计算数字 0 ,然后是下一行一个它抛出一个错误,无法将其转换为浮点数( ValueError:无法将字符串转换为浮动),可能导致它尝试转换 \ 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: 

1 个答案:

答案 0 :(得分:4)

当您使用for row in f_content:时,您会将每一行视为"4\n"。然后,当您使用.splitlines()时,您将获得["4", ""]。 4可以很好地转换,但没有办法将空字符串转换为浮点数。相反,不要做你的for length in row:;直接使用row; float()并不介意换行符:

>>> x = '4\n'
>>> float(x)
4.0
>>> first, second = x.splitlines()
>>> first
'4'
>>> second
''
>>> float(first)
4.0
>>> float(second)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: could not convert string to float:

这会使你的循环看起来像这样:

for length in f_content:
    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)

我将for row in f_content更改为for length in f_content,因此我不需要将所有length替换为row