ABSP, Ch 8, Practice Project #2

My solution to the Practice Project #2 in Chapter 8 of the excellent book “Automate the Boring Stuff with Python” (ABSP)

#! usr/bin/env python3
# by lorenzo - 17/08/2017
# 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.

def listToString(aList):
    text = ''
    for i in range(len(aList)):
        text += aList[i]
    return text

def Replace(aList, length):
    for i in range(length):
        del aList[-1]

def addToList(aString, aList):
    for i in range(len(aString)):
    return aList

print("Enter location of file to read:")
location = input()
myFile = open(location, 'r')
myContent = myFile.read()
myList = []

for i in range(len(myContent)):
    aPiece = listToString(myList) 
    if aPiece.endswith('ADJECTIVE'):
        print('Enter an adjective:')
        adjective = input()
        Replace(myList, 9)
        addToList(adjective, myList)
    elif aPiece.endswith('NOUN'):
        print('Enter a noun:')
        noun = input()
        Replace(myList, 4)
        addToList(noun, myList)        
    elif aPiece.endswith('ADVERB'):
        print('Enter an adverb:')
        adverb = input()
        Replace(myList, 6)
        addToList(adverb, myList)        

    elif aPiece.endswith('VERB'):
        print('Enter a verb:')
        verb = input()
        Replace(myList, 4)
        addToList(verb, myList)         

thisFile = open('madlibs.txt', 'w')

Comments about the code are welcome.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s