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:
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
Since you want to calculate the sum of the numbers after you find them It's better to use a generator expression with
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))