【问题标题】:Can't split multi-line string into an array of rows无法将多行字符串拆分为行数组
【发布时间】: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


【解决方案1】:

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

>>> 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,这样我就不需要用row 替换所有出现的length

【讨论】:

  • 我试过了,但它不起作用。你能举个例子吗?我不再收到错误消息,但它只是偶尔显示第一个数字的输出,然后什么也不做。
  • @ThomasTom:我进行了编辑以显示您的代码现在应该是什么样子。这行得通吗?
猜你喜欢
  • 2018-05-01
  • 2016-12-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多