0

I am trying to find the words NOUN|ADJECTIVE|VERB in the file, and then prompt the user to enter new words and replace the words with the user input, which I'll write to a new text file.

It almost works, but the text file I am using (which has 2 nouns) prompts the user for both of the 2 nouns, yet whatever the input for the first NOUN was is outputted in both noun positions in the file.

For example:

Please enter a: ADJECTIVE
blue

Please enter a: NOUN
cup

Please enter a: VERB
go

Please enter a: NOUN
coat

The blue panda walked to the cup and then go. A nearby cup was unaffected by these events.

pattern = re.compile(r'(NOUN|ADJECTIVE|VERB)') #sets pattern
with open('story.txt', 'r') as f: #opens file to read
    contents = f.read() #assigns readable info to variable
    matches = pattern.findall(contents) #makes list of matches
for match in matches: #iterate over every match
    cual = str(match) 
    print("Please enter a:", cual) 
    replacement = input() #get input to replace the match
    contents = contents.replace(match, replacement) #replace with input
f.close() 
with open('story2.txt', 'w') as g: #write new text into new file
    g.write(contents)
g.close()
with open('story2.txt', 'r') as f:
    finished = f.read()
    print(finished) #print new text
4
  • You are replacing all occurrences of e.g. NOUN with the value input by the user. Try adding ,maxreplace=1 to the contents.replace() parameters. Commented Dec 16, 2019 at 7:40
  • Can you show us a few lines from the story.txt? Commented Dec 16, 2019 at 7:44
  • The ADJECTIVE panda walked to the NOUN and then VERB. A nearby NOUN was unaffected by these events. Commented Dec 16, 2019 at 7:45
  • @barny Where, specifically, do I add it? I tried adding it after the other 2 arguments but it gave an error message. I guess I'm adding it to the wrong place. Commented Dec 16, 2019 at 7:48

1 Answer 1

1

@Remitto try this:

contents = contents.replace(match, replacement, 1)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.