Write a random word-replacement program, similar to the mad-lib game which children enjoy. The input consists of a series of word lists, followed by some text into which words are substituted from the lists at random.
The first section is a series of one or more lists of words, each given on a single line as a series of blank-separated words. The words may be separated by any number of blanks. Words may not contain blanks.
This section is terminated by a line consisting of only a -.
The second section is a series of lines which are are copied to the output, some of which after replacement by a random word from the substitution list. Any construct consisting of a number sign (#) followed by at least one digit is to be replaced with a word from the corresponding list. Nothing else is to be replaced. The number following the number sign refers to one of the lists from the first section, numbered starting from zero up to the number of lists less one. This item should be replaced by one chosen randomly from the list indicated by the number. If the number is out of range, substitute the word [error] instead of choosing from a list.
For instance:
The program should read and store the replacement section without producing any output. It should then copy the lines in the second section to the output with replacement. When choosing replacement words, a word should be chosen from the correct list with equal probability for each word. In general, each run of the program will produce different output. Some possibilities from the above input are:
Note: You must read from standard input. Your program may not open a file.
Do not substitute words in the substitution lists. That is, #3 specifies a substitution when it appears in the second section. If it appears in a word list in the first section, it's just a word that can be printed if the random process selects it.
You probably want to read the input one line at a time. The easiest way is to use two successive loops, one for the first section and one for the second. The first loop ends after reading the - line, and the second ends at the end of the file. Store the replacement words in a list of lists. Create an empty list at the start of your program. In the first loop, read each line, then split the line to make an array of strings. Use append or something similar to add this new list to the end of the main list. When the first loop finishes, you will have a list of all your replacement lists.
In the second loop, read each line and search for #. When you find one, find the digits that follow it. Convert the digits to an integer, and use it to find the replacement list. Use Python's Random module to choose a word at random from the selected list.