Rob Salzman
Rob Salzman

Reputation: 51

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 through 9.

Alphanumeric strings (strings including both numbers and letters) are not to be included in the summation.

This is the content of the file:

a b cddde ff 1
5
hH five lll 0
l 10
99 abcd7
9kk
0

So the answer would be 115 in this case.

Upvotes: 1

Views: 3971

Answers (3)

Teodorico Levoff
Teodorico Levoff

Reputation: 1659

def function():

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

    total = 0

    for i in wordList:
        if i.isnumeric():
            total += int(i)
    return total

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.

Upvotes: -3

Mark Skelton
Mark Skelton

Reputation: 3891

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 = 0

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

Upvotes: 2

Remi Guan
Remi Guan

Reputation: 22282

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

Upvotes: 3

Related Questions