简体   繁体   中英

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.

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)

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

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 ie 'a' as an int.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM