portable fortune program

Chris Liechti cliechti at gmx.net
Sat Apr 27 13:56:46 EDT 2002


joost_jacob at hotmail.com (J.Jacob) wrote in 
news:13285ea2.0204270857.2f34f8a4 at posting.google.com:

> I have always liked the unix fortune program.
> Unfortunately nowadays some *n.x's come without fortune,
> and sometimes I have to work with Windows.  I wanted to be
> able to do:
>     C:\mydirectory> python -c "import fortune; fortune.quote()"
> printing a nice quote to stdout.
> The fortune module has to be able to locate a file with
> the name 'allfortunes'.  And you want everything to be
> portable.  And working with python 1.5.2 too.
> 
> The allfortunes file contains quotes separated by lines
> with a '%' as its first character.  I downloaded a couple
> of BSD fortune files and combined them into allfortunes.
> If you put the following fortune.py file with an
> allfortunes file into one of the directories in your
> sys.path, or in you current working directory, it will work.
> 
> This is a first hack, it is slow, the allfortunes file is
> not compressed, so comments are welcome, maybe you can
> suggest improvements?  I was trying to put the allfortunes
> file into a compressed string at the end of the fortune.py
> file, so you do not need a separate file anymore, but I
> did not see a best way to do it.  Please let me know if it
> does not work with your python distribution.
> 
> joost_jacob at hotmail.com
> 
> 
> 
> # file fortune.py
> import random, os
> 
> def randlistindex(yourlist):
>     "Return a random index number into yourlist"
>     return random.randint(0, len(yourlist)-1)

why not use random.choice(seq)?
quote docs:"""Return a random element from the non-empty sequence seq."""
 
> def quote():
>     """
>     Return a quote <string> from file allfortunes,
>     assume the file allfortunes is located in the same
>     directory as this module."""
>     datafile = os.path.join(
>       os.path.dirname(__import__(__name__).__file__),
>       'allfortunes' )
>     quotesfile = open(datafile)
>     quoteslist, quote = [], ''
>     for s in quotesfile.readlines():

readelines loads all into memory... either use xreadlines or the
new "for line in file" feature of py 2.2 when dealing with large files.

when you don't care to load everything into memory something like this 
might work:

>>> quoteslist = quotesfile.read().split('%')

and maybe applying strip to each quote to remove whitespaces from begin and 
end of quote.

>>> quoteslist = map(string.strip, quoteslist)


>         if s[0] == '%':
>             if quote:
>                 quoteslist.append(quote)
>                 quote = ''
>         else: quote = quote + s
>     if quote: quoteslist.append(quote)
>     print quoteslist[randlistindex(quoteslist)],
> 



-- 
Chris <cliechti at gmx.net>




More information about the Python-list mailing list