Story generator....

Tim Chase python.list at tim.thechases.com
Mon Dec 3 13:15:48 EST 2007


> i am not sure if this is at all possible.... i am trying to make a story
> generator.... like the ones that i did in elementry school where they would
> supply a story with blanks and you  would have to place the nouns-verbs/you
> best friends name and it would make a funny story.

Sounds like your typical Mad Libs type game.

##############################################
class ThingGetter1(object):
   def __getitem__(self, category):
     s = raw_input("Please enter a %s:  " % category)
     return s
story1 = """
Dear %(person name)s,
Thank you for the %(gift)s.
It was very %(description)s.
Love,
%(your name)s
"""
print story1 % ThingGetter1()

# another smarter method
class ThingGetter2(object):
   def __init__(self):
     self.cache = {}
   def __getitem__(self, category):
     if category in self.cache:
       return self.cache[category]
     s = raw_input("Please enter a %s:  " % category)
     self.cache[category] = s
     return s
story2 = """
Once there was this %(first noun)s
who lived in a %(second noun)s down near %(place)s.
The %(first noun)s was very %(adj)s.
The %(adj)s %(first noun)s liked to %(verb)s
the %(second noun)s every %(time period)s.
"""
print story2 % ThingGetter2()
###############################################


Each has its own behaviors, with the latter being a little more 
friendly towards back-referencing.

-tkc






More information about the Python-list mailing list