-1

I'm working on the assignment of a Python course in Coursera that involves using regular expressions. It tells us to

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

The data we use is this

Here's my code:

import re
handle = open('regex_sum_330187.txt')
for line in handle :
    line = line.rstrip()
    numbers = re.findall('([0-9]+)',line)

print(sum(numbers))

It turns out that the sum is 0. So I'm a bit confused. If re.findall() is supposed to return a list of zero or more substrings, what's wrong with my code?

saeed foroughi
  • 1,662
  • 1
  • 13
  • 25
Wan Jou Shao
  • 3
  • 1
  • 1
  • 2

2 Answers2

1

It looks like you're just summing the last line. Why not move the summing inside the loop?

import re
handle = open('regex_sum_330187.txt')
numbers = 0
for line in handle:
    line = line.rstrip()
    numbers = numbers + sum(map(lambda x: int(x), re.findall('([0-9]+)', line)))

print(numbers)
wogsland
  • 9,106
  • 19
  • 57
  • 93
0

try this:

handle = open('regex_sum_330187.txt')
numbers = re.findall(r'[1-9]*',handle)
new_list = []
for i in numbers :
    if i :
        i = int(i)
        new_list.append(i)
print(sum(new_list))
Negar37
  • 352
  • 1
  • 8