How to sum all the numbers in a text file?

前端 未结 3 1834
误落风尘
误落风尘 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 02:46

    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)
    

提交回复
热议问题