I am just learning python and need some help for my class assignment.
I have a file with text and numbers in it. Some lines have from one to three numbers and other
My first attempt to answer with the use of regular expressions, I find it a great skill to practise, that reading other's code.
import re # import regular expressions
chuck_text = open("regex_sum_286723.txt")
numbers = []
Total = 0
for line in chuck_text:
nmbrs = re.findall('[0-9]+', line)
numbers = numbers + nmbrs
for n in numbers:
Total = Total + float(n)
print "Total = ", Total
and thanx to Beer for the 'comprehension list' one liner, though his 'r' seems not needed, not sure what it does. But it reads beautifully, I get more confused reading two lots of loops like my answer
import re
print sum([int(i) for i in re.findall('[0-9]+',open("regex_sum_286723.txt").read())])
import re
print sum([int(i) for i in re.findall('[0-9]+',open(raw_input('What is the file you want to analyze?\n'),'r').read())])
You can compact it into one line, but this is only for fun!