Notification texts go here Contact Us Buy Now!

How to extract all the numbers from a text file using re.findall() and compute the sum using a for-loop?

```html

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 since sum(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 since int cannot be directly applied to iterables, I used map(int, ...).

```

Post a Comment

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.