Reputation: 53
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
Upvotes: 0
Views: 92
Reputation: 917
@Remitto try this:
contents = contents.replace(match, replacement, 1)
Upvotes: 1