Newbie question: Any way to improve this code?

Scott David Daniels Scott.Daniels at Acm.Org
Sun Dec 7 01:20:55 CET 2003


Gustavo Campanelli wrote:
> I'm begining to work in a program that cicles through a list of phrases 
> (basically, a changing signature file). I started yesterday, and I only 
> have abput 8 full hours of real Python experience.
Too much fun.  I wrote a random quote generator.  Spec is to to pull
a quote from a quote file at random, with each quote appearing equally
often.  I threw in a command line arg to seed the RNG or replace the
quote file name.

Try it yourself before looking below (I'll wait).

import sys, random

def choose_quote(args=None):
     """Choose a quote at random from a quote file.

     args should be a list of string arguments. Args begins with '@'
     are used to seed the random number generator.  Otherwise the
     arg is presumed to be the quote file name.  If args is passed
     in as None, args is grabbed from sys.argv (the command line).
     """

     quotefile = SOURCE
     best, quote = -1.0, 'Sorry, no quote today.  -- the Management'

     if args is None:
         args = sys.argv[1:]
     for arg in args:
         if arg.startswith('@'):
             random.seed(arg)
         else:
             quotefile = arg

     try:
         source = file(quotefile)
     except IOError, e:
         print >>sys.stderr, 'I cannot seem to read %r.' % quotefile
     else:
         # The file is open.  Choose the line with the highest score.
         # Each line is assigned a value by random(), any of which is
         # greater than the initial -1.  This gives each line in the
         # file an equal chance of being chosen.
         try:
             for line in source:
                 score = random.random()
                 if score > best:
                     best, quote = score, line
         except IOError, e:
             print >>sys.stderr, 'Error reading file %r.' % quotefile
             # Treat any I/O error as EOF. We may already have a quote.
         source.close()
     return quote.strip()



if __name__ == '__main__':
     print choose_quote()


-Scott David Daniels
Scott.Daniels at Acm.Org




More information about the Python-list mailing list