Advertisement
Guest User

Untitled

a guest
Feb 6th, 2016
40
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.42 KB | None | 0 0
  1. """
  2. madlib2.py
  3. Interactive display of a mad lib, which is provided as a Python format string,
  4. with all the cues being dictionary formats, in the form {cue}.
  5.  
  6. In this version, the cues are extracted from the story automatically,
  7. and the user is prompted for the replacements.
  8.  
  9. Original verison adapted from code of Kirby Urner
  10. """
  11.  
  12. def getKeys(formatString):
  13. '''formatString is a format string with embedded dictionary keys.
  14. Return a set containing all the keys from the format string.'''
  15.  
  16. keyList = list()
  17. end = 0
  18. repetitions = formatString.count('{')
  19. for i in range(repetitions):
  20. start = formatString.find('{', end) + 1 # pass the '{'
  21. end = formatString.find('}', start)
  22. key = formatString[start : end]
  23. keyList.append(key) # may add duplicates
  24.  
  25. return set(keyList) # removes duplicates: no duplicates in a set
  26.  
  27. def addPick(cue, dictionary): # from madlibDict.py
  28. '''Prompt for a user response using the cue string,
  29. and place the cue-response pair in the dictionary.
  30. '''
  31. promptFormat = "Enter a specific example for {name}: "
  32. prompt = promptFormat.format(name=cue)
  33. response = input(prompt)
  34. dictionary[cue] = response
  35.  
  36.  
  37. def getUserPicks(cues):
  38. '''Loop through the collection of cue keys and get user choices.
  39. Return the resulting dictionary.
  40. '''
  41. userPicks = dict()
  42. for cue in cues:
  43. addPick(cue, userPicks)
  44. return userPicks
  45.  
  46. def tellStory(storyFormat):
  47. '''storyFormat is a string with Python dictionary references embedded,
  48. in the form {cue}. Prompt the user for the mad lib substitutions
  49. and then print the resulting story with the substitutions.
  50. '''
  51. cues = getKeys(storyFormat)
  52. userPicks = getUserPicks(cues)
  53. story = storyFormat.format(**userPicks)
  54. print(story)
  55.  
  56. def main():
  57. originalStoryFormat = '''
  58. Once upon a time, deep in an ancient jungle,
  59. there lived a {animal}. This {animal}
  60. liked to eat {food}, but the jungle had
  61. very little {food} to offer. One day, an
  62. explorer found the {animal} and discovered
  63. it liked {food}. The explorer took the
  64. {animal} back to {city}, where it could
  65. eat as much {food} as it wanted. However,
  66. the {animal} became homesick, so the
  67. explorer brought it back to the jungle,
  68. leaving a large supply of {food}.
  69.  
  70. The End
  71. '''
  72. tellStory(originalStoryFormat)
  73. input("Press Enter to end the program.")
  74.  
  75.  
  76. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement