user6561340 user6561340 - 1 year ago 45
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:
continue
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 = f.read()

total = sum(int(g.group(0)) for g in re.finditer(r'\d+', text))