如何使用 Python 3 中的读取行读取由 space 分隔的整数输入文件?

How to read an input file of integers separated by a space using readlines in Python 3?

我需要读取包含一行整数 (13 34 14 53 56 76) 的输入文件 (input.txt),然后计算每个数字的平方和。

这是我的代码:

# define main program function
def main():
    print("\nThis is the last function: sum_of_squares")
    print("Please include the path if the input file is not in the root directory")
    fname = input("Please enter a filename : ")
    sum_of_squares(fname)

def sum_of_squares(fname):
    infile = open(fname, 'r')
    sum2 = 0
    for items in infile.readlines():
        items = int(items)
        sum2 += items**2
    print("The sum of the squares is:", sum2)
    infile.close()

# execute main program function
main()

如果每个数字都在自己的行上,它就可以正常工作。

但是,当 所有数字都在一行上并由 space 分隔时,我不知道该怎么做。在那种情况下,我收到错误:ValueError: invalid literal for int() with base 10: '13 34 14 53 56 76'

您正在尝试将其中包含 spacesstring 转换为 integer .

你想要做的是使用 split 方法(在这里,它将是 items.split(' '),这将 return 一个 list 个字符串,包含数字,这次没有任何 space。然后您将遍历此列表,将每个元素转换为一个 int正在努力。

我相信你会找到接下来要做的事情。 :)


这是一个简短的代码示例,其中包含更多 pythonic 方法来实现您正在尝试做的事情。

# The `with` statement is the proper way to open a file.
# It opens the file, and closes it accordingly when you leave it.
with open('foo.txt', 'r') as file:
    # You can directly iterate your lines through the file.
    for line in file:
        # You want a new sum number for each line.
        sum_2 = 0
        # Creating your list of numbers from your string.
        lineNumbers = line.split(' ')
        for number in lineNumbers:
            # Casting EACH number that is still a string to an integer...
            sum_2 += int(number) ** 2
        print 'For this line, the sum of the squares is {}.'.format(sum_2)

您可以使用file.read()获取字符串,然后使用str.split按空格分割。

您需要先将每个数字从 string 转换为 int,然后使用内置的 sum 函数计算总和。

顺便说一句,您应该使用 with 语句为您打开和关闭文件:

def sum_of_squares(fname):

    with open(fname, 'r') as myFile: # This closes the file for you when you are done
        contents = myFile.read()

    sumOfSquares = sum(int(i)**2 for i in contents.split())
    print("The sum of the squares is: ", sumOfSquares)

输出:

The sum of the squares is: 13242

您可以尝试使用 split() 函数在 space 上拆分您的项目。

来自文档:例如,' 1 2 3 '.split() returns ['1', '2', '3'].

def sum_of_squares(fname):
    infile = open(fname, 'r')
    sum2 = 0
    for items in infile.readlines():
        sum2 = sum(int(i)**2 for i in items.split())
    print("The sum of the squares is:", sum2)
    infile.close()

保持简单,不需要任何复杂的东西。这是一个带注释的分步解决方案:

def sum_of_squares(filename):

    # create a summing variable
    sum_squares = 0

    # open file
    with open(filename) as file:

        # loop over each line in file
        for line in file.readlines():

            # create a list of strings splitted by whitespace
            numbers = line.split()

            # loop over potential numbers
            for number in numbers:

                # check if string is a number
                if number.isdigit():

                    # add square to accumulated sum
                    sum_squares += int(number) ** 2

    # when we reach here, we're done, and exit the function
    return sum_squares

print("The sum of the squares is:", sum_of_squares("numbers.txt"))

输出:

The sum of the squares is: 13242