Nov-17-2019, 12:36 AM
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
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?
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()