user6561340 user6561340 - 1 year ago 76
Python Question

Python list comprehensions with regular expressions on a text

I have a text file which includes integers in the text. There are one or more integers in a line or none. I want to find these integers with regular expressions and compute the sum.

I have managed to write the code:

import re
doc = raw_input("File Name:")
text = open(doc)
lst = list()
total = 0

for line in text:
nums = re.findall("[0-9]+", line)
if len(nums) == 0:
for num in nums:
num = int(num)
total += num
print total

But i also want to know the list comprehension version, can someone help?

Answer Source

Since you want to calculate the sum of the numbers after you find them It's better to use a generator expression with re.finditer() within sum(). Also if the size of file in not very huge you better to read it at once, rather than one line at a time.

import re
doc = raw_input("File Name:")
with open(doc) as f:
    text =

total = sum(int( for g in re.finditer(r'\d+', text))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download