portable fortune program

J.Jacob joost_jacob at hotmail.com
Mon Apr 29 10:19:33 EDT 2002


Thank you for your reply [Steve Holden] and the weblinks !
Also thanks to the other people who reacted.

A nicely optimized fortune-webserver will have to wait until i have
more solid ground under my feet when doing web programming.  I
noticed you wrote a book about webprogramming and i am considering
buying it $-) 

I did like to see the ideas for improvements.  The idea by [Michael
Gilfix] about reserving the same amount of space for each quote and
then using seek() is elegant.  At the moment i have a 3.2MB file
with 19930 quotes and i am thinking about an easy way to add/remove
quotes and maybe using the system's clipboard to be able to add
quotes from my own collection to usenet postings.

Here is a slightly improved version of fortune.py.  If there is no
allfortunes file it will use the modulequotes variable, it is easy
to add your favorite quotes to the modulequotes variable.  This
version keeps the quotes in memory when calling quote() or
getQuote() repeatedly from a program that loaded this module:


-----------------------------  fortune.py  ------------------------
import random, os, StringIO

modulequotes = """At the end of every pot of gold there's a rainbow
%
To a three year old with a hammer, everything looks like a nail
%
"""

quoteslist = []

def getQuote():
    """
    Return a quote <string> from file allfortunes,
    assume the file allfortunes is located in the same
    directory as this module."""
    try:
        datafile = os.path.join(
          os.path.dirname(__import__(__name__).__file__),
          'allfortunes' )
        quotesfile = open(datafile)
    except IOError:
        quotesfile = StringIO.StringIO(modulequotes)
    quote = ''
    if not quoteslist:
        for s in quotesfile.readlines():
            if s[0] == '%':
                if quote:
                    quoteslist.append(quote)
                    quote = ''
            else: quote = quote + s
        if quote: quoteslist.append(quote)
    return random.choice(quoteslist)

def count(): return len(quoteslist)

def quote(): print getQuote(),
-------------------------------------------------------------------


Joost Jacob
www.liacs.nl/~jjacob/

YAY i can add a quote now even when using Windows:
The outraged husband discovered his wife in bed with another man.
        "What is the meaning of this?" he demanded.  "Who is this fellow?"
        "That seems like a fair question," said the wife, rolling over.
"What IS your name?"

<omg-where-is-the-option-to-prevent-offensive-quotes-'ly-yrs>



More information about the Python-list mailing list