[Tutor] Looking for a number adding script
jfouhy at paradise.net.nz
jfouhy at paradise.net.nz
Mon Apr 11 05:25:30 CEST 2005
Quoting Kenny Li <kenny.li at gmail.com>:
> A little while ago, when I tried to pick up Python, I ran into an
> article that has a script to add up all numbers in a text file (email
> message, for example). I want to use that script now, but I could not
> find (recalled) the URL to the article. If you have a point, please
> let me know. Appreciate it.
I don't have the original one you saw ...
But this is a problem very well suited to regular expressions. Python's re
module has good documentation on regular expression syntax.
example:
------------------------- sumFile.py ---------------------------
import sys, re
if len(sys.argv) < 2:
print 'Syntax: python sumFile.py <filename>'
sys.exit(1)
filename = sys.argv[1]
numexp = re.compile(r'\d+(?:\.\d+)?') # Match one or more digits, optionaly
followed
# by (a ., followed by one or more digits).
# Note that ".18" will be treated as
"18", not
# "0.18" (unless it really is "0.18" in
the text).
print 'Sum: ', sum(map(float, numexp.findall(file(filename).read())))
--
John.
More information about the Tutor
mailing list