-5

I will read through and parse a file with text and numbers. I will extract all the numbers in the file and compute the sum of the numbers.

Data Files: http://python-data.dr-chuck.net/regex_sum_361580.txt

My code is:

import re

sum = 0

file = open('regex_sum_361580')
for line in file:
    numbers = re.findall('[0-9]+', line)
    if not numbers:
        continue
    else:
        for number in numbers:
            sum = int(number)

print (sum)

Also, is there an easier way to solve this problem?

halfer
  • 19,824
  • 17
  • 99
  • 186

1 Answers1

-1

you forgot to increment the sum variable, you were just re initializing it and don't use keywords as variable names. Also make a habit of mentioning the mode in which you want to open the file.

import re

sum = 0

file = open('regex_sum_361580', 'r')
for line in file:
    numbers = re.findall('[0-9]+', line)
    if not numbers:
        continue
    else:
        for number in numbers:
            sum += int(number)

print (sum)
Amey Kumar Samala
  • 904
  • 1
  • 7
  • 20