【问题标题】:How to read an input file of integers separated by a space using readlines in Python 3?如何在 Python 3 中使用 readlines 读取由空格分隔的整数输入文件?
【发布时间】:2018-06-01 00:26:57
【问题描述】:

我需要读取一个包含一行整数 (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()

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

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

【问题讨论】:

  • 文件的具体内容是什么?
  • 如果只是一行,请致电data = infile.read(); for number in map(int, data.split()): sum2 += number ** 2
  • 您的文件是包含空格分隔数字的单行吗?
  • 是的,没错。这是文件的全部内容:13 34 14 53 56 76
  • @JonClements 是的,尽管对于家庭作业来说这可能有点太高级了。另外,不要忘记int(num) :-)

标签: python python-3.x integer readlines


【解决方案1】:

您可以使用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

【讨论】:

  • @JonClements 总是忘记这一点:)
  • OP 可以在不被怀疑抄袭/不当行为的情况下上交 KISS 解决方案怎么样 ;-)
  • 如果您打开文件(演示with 语句)并在此处获取contents 可能会很好:)
【解决方案2】:

您正在尝试将包含 空格 的 字符串 转换为 整数。

你想要做的是使用 split 方法(这里是 items.split(' '),它将返回一个 list 字符串,包含数字,没有任何这次留出空间。然后您将遍历此列表,将每个元素转换为 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)

【讨论】:

    【解决方案3】:

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

    来自文档:例如,' 1 2 3 '.split() 返回['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()
    

    【讨论】:

    • 对...但是如果你尝试这个 - 你会得到一个错误,因为 items = int(items.split()) 是一个列表,你将无法将它转换为 int - 你想要遍历该列表并转换每个项目,然后添加...
    • 谢谢,很好的收获@JonClements。看起来 Farhan.K 现在已经更新了他的答案来涵盖这个案例。
    • 如果他在区分列表、字符串、整数等方面存在问题,我仍然不相信他具备理解这种单行表达式的知识。
    【解决方案4】:

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

    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
    

    【讨论】:

      猜你喜欢
      • 2015-03-08
      • 2011-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-12
      • 1970-01-01
      • 2021-02-17
      相关资源
      最近更新 更多