How to sum all the numbers in a text file?

前端 未结 3 1858
误落风尘
误落风尘 2020-12-22 02:03

I have to calculate the sum of any numbers in the file and print the sum.

A number is defined as any string beginning with a digit 0 through 9 followed by any numbe

3条回答
  •  甜味超标
    2020-12-22 03:02

    I'd suggest that use RegEx:

    import re
    
    with open('file') as f:
        print(sum(int(i) for i in re.findall(r'\b\d+\b', f.read())))
    

    In this case:

    • \b+ match all the numbers, and \b checks if there a letter after (or before) the number so we can ignore abcd7 or 9kk.

    • re.findall() try to find all the numbers in the file use the RegEx \b\d+\b and returns a list.

    • A list compression, int(i) for i in re.findall(r'\b\d+\b'), convert all the elements in the list which returned by re.findall() to int object.

    • sum() built-in function sums the elements of a list, and returns the result.

    Online RegEx demo

提交回复
热议问题