Shuairan Shuairan - 2 years ago 398
Python Question

How to join() - chapter 8 Automate the Boring Stuff

From Automate The Boring Stuff With Python book:
"Create a Mad Libs program that reads in text files and lets the user add their own text anywhere the word ADJECTIVE, NOUN, ADVERB, or VERB appears in the text file. For example, a text file may look like this:

The ADJECTIVE panda walked to the NOUN and then VERB. A nearby NOUN was
unaffected by these events.

The program would find these occurrences and prompt the user to replace them."

I'm almost done, but I can't seem to figure out how to .join the last list on the file. I've looked online and tried the methods. Instead of getting a string out of join, I get the whitespace in ' '.join(mod4) separating the letters within each list string value.
[ ' A n ' , ' o n e ' , ' t w o ' , ' a n d ' , ' t h r e e ' , ' f o u r ' ]
Everything else does the job.

#! python3

import re

madText = open('madText.txt', 'w')



content = list(text.split(' '))

for i in content:

if i == "ADJECTIVE":
replaceRegex1 = re.compile(r'(ADJECTIVE)')
print('Enter an ADJECTIVE:')
ADJECTIVE = input()
mod1 = replaceRegex1.sub(ADJECTIVE, str(content))

elif i == "NOUN":
replaceRegex2 = re.compile(r'(NOUN)')
print('Enter a NOUN:')
NOUN = input()
mod2 = replaceRegex2.sub(NOUN, str(mod1))

elif i == "ADVERB":
replaceRegex3 = re.compile(r'(ADVERB)')
print('Enter an ADVERB:')
ADVERB = input()
mod3 = replaceRegex3.sub(ADVERB, str(mod2))

elif i == "VERB":
replaceRegex4 = re.compile(r'(VERB)')
print('Enter a VERB:')
VERB = input()
mod4 = replaceRegex4.sub(VERB, str(mod3))

content = ' '.join(mod4) # Look here.
madLibs = open('madText2.txt', 'w')

Answer Source

You have a basic assumption that is preventing you from completing this. Your assignment of mod4 is based on previous assignments and their order.

Instead what you should be doing is initializing an output variable to [] and appending the words to it as you loop through content. You would add your adlib words along with the real words.

Once you have built your output list, then you use join to turn that output into a string.

Also, using regex is overkill. Let's assume you've made an output = [] before the loop.

if i == 'NOUN':
   print('Enter a NOUN:')
   noun = input()  # raw_input() on Python 2
   output += noun

Now as you hit each adlib token you replace it with the inputted text and build your output list.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download