Randomly replace certain words in python using a dictionary

  dictionary, python, random, word

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()

Thank you in advance

Source: Python Questions

LEAVE A COMMENT