代码之家  ›  专栏  ›  技术社区  ›  kroneckersdelta

用python对文件中的整数求和

  •  1
  • kroneckersdelta  · 技术社区  · 7 年前

    文本文件。txt包含

    12 34 55     22 (tab)
    3
    5
    6
    7 13
    

    我知道如何从只包含由换行符分隔的整数的文件求和,

    f=open('txtfile.txt')
    sum = 0
    for i in f:
            sum += int(i)
    

    从一行求和(用空格或制表符分隔)

    linesum = 0
    aa=f.readline()
    bb=aa.split()
    
    for el in bb:
        nr = int(el)
        linesum += nr
    

    在textfile的第一行运行这个。txt返回123。

    我遇到的问题是将这两者结合起来,得到由换行符、空格和制表符分隔的整数之和。

    我想让程序在包含超过1个整数的行上使用linesum程序,否则我想使用linebreak sum程序。 然而,我在将这两个for循环推广到一个程序中时遇到了问题,该程序将检查这两个for循环中的哪一个将被使用。 非常感谢您的指导。

    1 回复  |  直到 7 年前
        1
  •  2
  •   GaneshTata    7 年前

    您可以使用python的 re 要对文件中的所有数字求和的模块:

    In [1]: import re
    
    In [2]: text = open('input_file.txt').read() # Read from file
    
    In [3]: text
    Out[3]: '12 34 55     22 (tab)\n3\n5\n6\n7 13\n'
    
    
    In [4]: list_numbers = re.findall('\d+', text) # Extract all numbers using the regex '\d+', which matches one, or more consecutive digits
    
    In [5]: list_numbers
    Out[5]: ['12', '34', '55', '22', '3', '5', '6', '7', '13']
    
    In [6]: sum([int(number) for number in list_numbers]) # Find the sum of all the numbers
    Out[6]: 157
    

    使用refidle的正则表达式匹配- refiddle demo