Search code examples
pythonpython-re

madLibs.py Automate the boring stuff


I am new to python, currently reading 'Automate the Boring Stuff' in Chapter 8 exercise:

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.

I have been strugling with the replacement part in my code, and now i'm getting this error:

newText = REGEX.sub(i, replaceItem, textContent) TypeError: 'str' object cannot be interpreted as an integer

import re

textFile = open('C:\\Users\\Cris\\madLibStory.txt')
textContent = textFile.read()
#fileName = os.path.basename('C:\\Users\\Cris\\madLibStory.txt')
textFile.close()

REGEX = re.compile(r'(ADJECTIVE|NOUN|VERB)')
matches = REGEX.findall(textContent)
print(matches)

for i in matches:
    replaceItem = input('Insert substitute for %s: ' %i)
    newText = REGEX.sub(i, replaceItem, textContent)

print(newText)
file = open('C:\\Users\\Cris\\madLibStoryLIBED.txt', 'w')
file.write(newText)
file.close()

Solution

  • The third parameter to Pattern.sub is an int type called count.

    Perhaps you wanted to use re.sub() rather than REGEX.sub(), which does accept three string parameters before the optional args.