4
\$\begingroup\$

Given a text file including different text and integer numbers (text.txt), what's the shortest way of getting the sum of all the numbers out if it? I have:

import re

f = open('text.txt', 'r')
result = 0
for line in f.readlines():
    for value in re.findall('[0-9]+', line):
        result += int(value)
f.close()
print(result)

Which works, but I would like to understand what are the possibilities to make it shorter?

\$\endgroup\$
1
  • \$\begingroup\$ You could make it shorter but you're going to sacrifice readability along the way. \$\endgroup\$ – James Buck Apr 16 '16 at 9:28
7
\$\begingroup\$

You can use map and sum. It good practice to use with statement when working with a file.

with open('text.txt', 'r') as f:
    result = sum(map(int, re.findall(r'[0-9]+', f.read())))

print(result)
\$\endgroup\$
1
  • \$\begingroup\$ I doubt the regex is necessary. What is fileted out? \$\endgroup\$ – Martin Thoma Aug 6 '20 at 18:40
5
\$\begingroup\$

read instead of readlines will read the whole file into a single string. Using the file within a context avoids calling close(). The generator expression shortens the remaining loop. sum does what you'd expect:

import re

with open('text.txt', 'r') as f:
    result = sum(int(value) for value in re.findall('[0-9]+', f.read()))
print(result)
\$\endgroup\$
2
  • \$\begingroup\$ I think you missed a sum call. \$\endgroup\$ – James Buck Apr 16 '16 at 9:31
  • \$\begingroup\$ Thx for attention. Corrected it ;) \$\endgroup\$ – schwobaseggl Apr 16 '16 at 9:31
1
\$\begingroup\$

\d instead of [0-9] saves a little.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy