Python list comprehensions with regular expressions on a text
<p>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.</p>

<p>I have managed to write the code:</p>

<pre><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
</code></pre>

<p>But i also want to know the list comprehension version, can someone help?</p>

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

<pre><code>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))
</code></pre>

python list-comprehension