Does anybody know how to modify this script so that it randomly changes the words when it finds them.
i.e not every instance of "Bear" becomes "Snake"
# A program to read a file and replace words
word_replacement = {'Bear':'Snake', 'John':'Karen', 'Bird':'Owl'}
with open("main.txt") as main:
words = main.read().split()
replaced = []
for y in words:
replacement = word_replacement.get(y, y)
replaced.append(replacement)
text = ' '.join(replaced)
print (text)
new_main = open("main.txt", 'w')
new_main.write(text)
new_main.close()
CodePudding user response:
One approach is to randomly decide to apply the replacement:
import random
replacement = word_replacement.get(y, y) if random.random() > 0.5 else y
In the example above it will change "Bear"
to "Snake"
(or any other words in word_replacement) with a ~0.5 probability. You can change the value to your desire randomness.
Putting all together:
# A program to read a file and replace words
import random
word_replacement = {'Bear': 'Snake', 'John': 'Karen', 'Bird': 'Owl'}
with open("main.txt") as main:
words = main.read().split()
replaced = []
for y in words:
replacement = word_replacement.get(y, y) if random.random() > 0.5 else y
replaced.append(replacement)
text = ' '.join(replaced)
print(text)
with open("main.txt", 'w') as outfile:
outfile.write(text)
Output (for Bear Bear Bear as main.txt)
Snake Bear Bear