How to extract all the numbers from a text file using re.findall() and compute the sum using a for-loop?
Assuming that you need to sum all the numbers in your txt:
total = 0
with open("regex_sum_167791.txt") as f:
for line in f:
total += sum(map(int, re.findall("\d+", line)))
print(total)
# 417209
Logics
To start with, try using with
when you do open
so that once any job is done, open
is closed.
Following lines are removed as they seemed redundant:
count = count+1
: Not used.line = line.rstrip()
:re.findall
takes care of extraction, so you don't have to worry about stripping lines.if len(x)!= 1 : continue
: Seems like you wanted to skip the line with no digits. But sincesum(map(int, re.findall("\d+", line)))
returns zero in such case, this is also unnecessary.num = int(x[0])
: Finally, this effectively grabs only one digit from the line. In case of two or more digits found in a single line, this won't serve the original purpose. And sinceint
cannot be directly applied to iterables, I usedmap(int, ...)
.