Skip to content Skip to sidebar Skip to footer

How To Sum All The Numbers In A Text File?

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 number of digits 0 t

Solution 1:

I'd suggest that use RegEx:

import re

withopen('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

Solution 2:

All you need to do is use item.isnumeric(). If the item made up of only numbers and not letters or other characters it will return true.

So you check the all the items in wordList and if the item isnumeric() you add the item to total.

infile = open(filename.txt, 'r')
content = infile.read()       
infile.close()

wordList = content.split()    
total = 0for item in wordList:
    if item.isnumeric():
        total += int(item)

Solution 3:

def function():

    infile = open("test.txt", 'r')
    content = infile.read()       
    infile.close()
    wordList = content.split()

    total = 0

    foriinwordList:
        ifi.isnumeric():
            total += int(i)
    returntotal

In this solution, I named the file test.txt. The idea is you loop through wordList which is a list containing every item spliced in test.txt (try printing wordList before the loop to see for yourself). We then try to cast each item as a int (this assumes no decimals will be in the file, if so you can include a float cast). We then catch ValueError which gets raised when casting i.e 'a' as an int.

Post a Comment for "How To Sum All The Numbers In A Text File?"