I'm doing a Python course and want to find all numbers in a text file with regular expression and sum them up. Now I want to try to do it with list comprehension.
import re
try:
fh = open(input('Enter a file Name: ')) #input
except:
print('Enter an existing file name') #eror
quit()
he = list() #store numbers
for lines in fh:
lines.rstrip()
stuff = re.findall('[0-9]+', lines)
if len(stuff) == 0: #skip lines with no number
continue
else:
for i in stuff:
he.append(int(i)) #add numbers to storage
print(sum(he)) #print sum of stored numbers
This is my current code. The instructor said its possible to write the code in 2 lines or so.
import re
print( sum( [ ****** *** * in **********('[0-9]+',**************************.read()) ] ) )
the "*" should be replaced.
This text should be used to practice:
Why should you learn to write programs? 7746 12 1929 8827 Writing programs (or programming) is a very creative 7 and rewarding activity. You can write programs for many reasons, ranging from making your living to solving 8837 a difficult data analysis problem to having fun to helping 128 someone else solve a problem. This book assumes that everyone needs to know how to program ...
I know the general concept of list comprehension but I have no idea what to do.
