【问题标题】:Can't convert strings to int or float无法将字符串转换为 int 或 float
【发布时间】:2021-07-13 16:51:38
【问题描述】:

所以我能够在你们的帮助下解决第一个问题,但现在程序运行没有任何错误,它没有正确计算平均值,我不知道为什么。这是它的样子:

def calcAverage():
with open('numbers.dat', 'r') as numbers_file:
    numbers = 0
    amount = 0

    for line in numbers_file:
        amount = amount + float(line)
        numbers += 1


average = amount / numbers
print("The average of the numbers in the file is:",average)

【问题讨论】:

  • 错误显示line 中有空字符串。如果您运行 float(''),则会收到 sam 错误
  • 您以错误的顺序运行代码 - 您必须在阅读下一行之前转换浮点数。
  • 到目前为止,正如@furas 所指出的那样,您错过了第一行,因为光标在每次readline 调用时都会前进。
  • 好的,谢谢你们解决了这个问题。感谢您的帮助!
  • 换行符 (\n) 或回车 (\r) 也会出现该错误。

标签: python


【解决方案1】:

您正在重新分配line 您检查linewhile 中是否为空。 while 测试正在测试文件中的上一行。

所以当你读到最后,你读取了一个空行并尝试将它添加到amount,但得到一个错误。

您也永远不会添加第一行,因为您在循环之前阅读它并且永远不会将其添加到amount

使用for 循环而不是while,循环结束时会自动停止。

def calcAverage():
    with open('numbers.dat', 'r') as numbers_file:
        numbers = 0
        amount = 0
    
        for line in numbers_file:
            amount = amount + float(line)
            numbers += 1
    
    average = amount / numbers
    print("The average of the numbers in the file is:",average)

如果您确实想使用while 循环,请这样做:

while True:
    line = numbers_file.readline()
    if not line:
        break

    # rest of loop

【讨论】:

【解决方案2】:

错误显示line 中有空字符串。

float('') 会出现同样的错误

您以错误的顺序运行代码 - 您在转换前一行之前读取了新行。
你应该去掉线,因为它仍然有\n

你需要

line = numbers_file.readline()
line = line.strip()  # remove `\n` (and `\t` and spaces)

while line != '':

    # convert current line
    amount = amount + float(line)  

    numbers += 1

    # read next line
    line = numbers_file.readline()
    line = line.strip()  # remove `\n` (and `\t` and spaces)

您也可以为此使用for-loop

numbers = []

for line in numbers_file:
    line = line.strip()  # remove `\n` (and `\t` and spaces)
    if line:
       numbers.append( float(line) )
    #else:
    #   break

average = sum(numbers) / len(numbers)

这可以简化为

numbers = [float(line) for line in numbers_file if line.strip() != '']

average = sum(numbers) / len(numbers)

【讨论】:

  • 我明白你的意思了,谢谢你的帮助
  • 在计算之前先在列表中收集输入(使用 numbers.append() 或 Pythons 构造列表理解)是一种可重用的方法/模式。
【解决方案3】:

其他答案说明了如何逐行读取文件。 其中一些处理了诸如到达文件结尾 (EOF) 和转换为浮点数的无效输入等问题。

由于任何 I/O 和 UI 都可能会提供无效输入,因此我想在按预期处理输入之前强调验证。

验证

对于从输入控制台或类似文件中读取的每一行,您应该考虑进行验证。

  • 如果字符串为会怎样? Converting an empty string input to float
  • 如果字符串包含 特殊字符 会怎样?喜欢commented by Mat
  • 如果号码不符合您预期的float,会发生什么情况? (取值范围,小数精度)
  • 如果没有读取或到达文件结尾会发生什么? (空文件或 EOF)

建议:为了使其健壮,预计输入错误并捕获它们。

(a) 在 Python 中使用 try-except 构造进行错误处理:

for line in numbers_file:
    try:
        amount = amount + float(line)
        numbers += 1
    except ValueError:
        print "Read line was not a float, but: '{}'".format(line)

(b) 预先输入测试: 以更简单的方式,您还可以使用基本的if 语句手动测试,例如:

if line == "":  # on empty string received
    print("WARNING: read an empty line! This won't be used for calculating average.")  # show problem and consequences
    continue  # stop here and continue with next for-iteration (jump to next line)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-10
    • 2013-03-02
    相关资源
    最近更新 更多