eigenbom

Python story generator.

Nov 18th, 2015
721
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.36 KB | None | 0 0
  1. from __future__ import print_function
  2. import sys, codecs, random, string, re
  3.  
  4. # just a simple story generator
  5. # let me know what you do with it
  6. # tweet -> @eigenbom
  7.  
  8. # expands a term, using a grammar and a world (a dictionary of concrete things)
  9. def expand(grammar, world, start_term):
  10.     m = re.search('[.*]', start_term)
  11.     e2 = start_term
  12.    
  13.     def repl(matchobj):
  14.         m = matchobj.group(1)
  15.         attrib = (matchobj.group(0)[0]=="$")
  16.            
  17.         matched = ((not attrib) and m in grammar) or (attrib and m in world)       
  18.         if not matched:
  19.             # not yet matched .. so hold off?
  20.             return matchobj.group(0)
  21.            
  22.         if attrib: e = world[m]
  23.         else: e = grammar[m]
  24.         replacement = None 
  25.         if type(e) is list:
  26.             replacement = random.choice(e)
  27.         elif hasattr(e, '__call__'): # if function
  28.             replacement = e(grammar, world, e2)
  29.         else:
  30.             replacement = e
  31.            
  32.         # if replacement is concrete, add it to the world ...
  33.         if not attrib:
  34.             world[m] = replacement
  35.             # pprint(world)
  36.         return replacement
  37.    
  38.     while True:
  39.         # then expand
  40.         e1 = re.sub('\[(\w*)\]', repl, e2)     
  41.         e1 = re.sub('\$(\w*)', repl, e1)
  42.         if e1 == e2: break
  43.         else: e2 = e1
  44.        
  45.     return e2
  46.  
  47. # shorthand
  48. def o(str):
  49.         return [s for s in str.split(",")]
  50.        
  51. def generate_story():
  52.     grammar = dict(
  53.         raised_by_2 = o("wolves,donkeys,goats"),
  54.         raised_by = o("[raised_by_2],violent [raised_by_2],happy [raised_by_2]"),
  55.         raise_location = o("forest,lake,ruins,marsh,castle,swamp"),
  56.         loc_adj = o("dark,pleasant,never-ending,smelly"),
  57.         raise_location_desc = o("[raise_location],[loc_adj] [raise_location]"),
  58.         raised_where = [
  59.             " in a [raise_location_desc]",
  60.             " near a [raise_location_desc]",
  61.             " nowhere near a [raise_location_desc]",
  62.             None],
  63.         raised = [
  64.             "was raised by [raised_by][raised_where]",
  65.             "grew up around [raised_by][raised_where]"],
  66.         major_skill = o("dance,socialise,paint"),
  67.         minor_skill = o("knit,sleep,criticise"),
  68.         growing_up_2 = [
  69.             " and [minor_skill]",
  70.             ", but $he was more interested in how to [minor_skill]",
  71.             " and, to a lesser extent, how to [minor_skill]",
  72.             ", but ate a lot of $fav_food",
  73.             " and eat $fav_food",
  74.             None
  75.         ],
  76.         growing_up = [
  77.             "The $raised_by_2 taught [him] how to [major_skill][growing_up_2]",
  78.             "$he learnt how to [major_skill][growing_up_2]",
  79.             "Early on, $he took a fascination to [major_skill][growing_up_2]"      
  80.             ],
  81.         enemy = o("a dragon,a ghost,a troll,a battletoad"),
  82.         enemy_action = [
  83.             " and stole [his] $fav_food.", 
  84.             ", demanding that $he $major_skill.",          
  85.             " and smiled.",
  86.         ],
  87.         event = ["[enemy] appeared[enemy_action]", "nothing much happened"],
  88.         event_start = ["One day, ", "Once, while wandering in the $raise_location, ", "Minding [his] own business, suddenly ", None],
  89.         story = "$he [raised]. [growing_up]. [event_start][event].",
  90.        
  91.         # helpers
  92.         him = lambda g,w,_: "him" if w["he"]=="he" else "her",
  93.         his = lambda g,w,_: "his" if w["he"]=="he" else "her",
  94.     )
  95.    
  96.     world = {}
  97.     # add a few details
  98.     world["he"] =  "he" if random.random()>0.5 else "she"
  99.     world["fav_food"] = random.choice(["spaghetti","weetbix","sandwich","pies"])
  100.    
  101.     history = expand(grammar, world, "[story]")
  102.     sentences = [s.strip() for s in history.split(".")]
  103.     sentences = [s.capitalize() + "." for s in sentences if len(s)>0]  
  104.     history = " ".join(sentences).strip()
  105.     return history
  106.  
  107. if __name__=="__main__":   
  108.     print(generate_story())
Advertisement
Add Comment
Please, Sign In to add comment