Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Mad Libs Program
#11
I have redone the program using the regular expression modules and it seems to work however I still need to hard code any new phrases in new stories. I would like to have it search the selected documents for capital phrases.

My thought was to replace

regex = re.compile(r'(ADJECTIVE)|(NOUN)|(VERB)|(BODY PART)|')
with

regex = re.compiler'[A-Z]{2,10}, ')
However this causes an output of
Quote:Enter a: N
Enter a: O
Enter a: U
Enter a: N
Enter a: A
Enter a: D
Enter a: J
Enter a: E
Enter a: C
Enter a: T
Enter a: I
Enter a: V
Enter a: E

The program is finding each capital letter and looking to replace it however I want to replace entire words. Any suggestions on how to fix this?

import re, os, random, pprint
#Change the working directory to the Mad Libs base folder.
os.chdir('/My Directory')
story = open(random.choice(os.listdir('/My directory')))#randomly Select a Story to be opened from the File.
storyContent = story.read()#save the story selected as a string
story.close()#close the selected story
name = input('Please Enter your name: ') #enter a name to be used in the save function
regex = re.compile(r'(ADJECTIVE)|(NOUN)|(VERB)|(BODY PART)|')#Enter in all the possible words that could be found.
for i in regex.findall(storyContent):#for each instance found the the compile
    for j in i:#needed to exit when nothing is found
        if j != '': # if there is a value found in j then ask for an inputed word
            phrase = re.compile(r'{}'.format(j)) #create a string of the value found in j
            replacementWord = input('Enter a: %s ' %j) #user enter a string of the type found in j
            storyContent = phrase.sub(replacementWord, storyContent, 1) # sub the user input into the story, replacing the phrase stored in the phrase string.
pp = pprint.PrettyPrinter(width=75, compact=True)
pp.pprint(storyContent) #print the story
newStory = open('/mydirectory'+ name, 'w')#save the story in a different folder
newStory.write(storyContent)
newStory.close()
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Running 3rd party libs on Steam Deck (Arch Linux) with restricted access metulburr 0 1,838 Jan-07-2023, 10:41 PM
Last Post: metulburr
  How can I use CRC libs in python? blodht 0 1,647 Feb-03-2020, 10:26 PM
Last Post: blodht
  using py32, just need py64 LIBS for now, how to install? davecotter 1 2,282 Jan-29-2019, 10:40 PM
Last Post: davecotter
  [split] adding 3rd party libs Blue Dog 7 6,828 Oct-22-2016, 12:03 PM
Last Post: Blue Dog

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020