portable fortune program
Jacob Hallen
jacob at boris.cd.chalmers.se.cd.chalmers.se
Sun Apr 28 15:17:36 EDT 2002
In article <z4Xy8.72324$z55.71416 at atlpnn01.usenetserver.com>,
Steve Holden <sholden at holdenweb.com> wrote:
>"J.Jacob" <joost_jacob at hotmail.com> wrote in message
>news:13285ea2.0204270857.2f34f8a4 at posting.google.com...
... Complicated suggestion by Steve deleted.
>>
>> # file fortune.py
>> import random, os
>>
>> def randlistindex(yourlist):
>> "Return a random index number into yourlist"
>> return random.randint(0, len(yourlist)-1)
>>
>> 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():
>> if s[0] == '%':
>> if quote:
>> quoteslist.append(quote)
>> quote = ''
>> else: quote = quote + s
>> if quote: quoteslist.append(quote)
>> print quoteslist[randlistindex(quoteslist)],
Simple suggestion by me added:
1. Get the size of the file.
2. Get a random number 0 - size-1.
3. Index to this point in the file.
4. Iterate back to the nearest previous '%'.
5. Print fortune from there.
This will of course skew the probability of getting printed towards longer
cookies, but nobody will notice that.
Jacob Hallén
--
More information about the Python-list
mailing list