使用替换字典随机替换文件中的某些单词

Random replacement of certain words in a file using a dictionary of replacements

有谁知道如何修改这个脚本,以便它在找到单词时随机更改它们。

也就是说,并不是所有的“熊”都会变成“蛇”

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

一种方法是随机决定应用替换:

import random
replacement = word_replacement.get(y, y) if random.random() > 0.5 else y

在上面的示例中,它会将 "Bear" 更改为 "Snake"(或 word_replacement 中的任何其他词),概率约为 0.5。您可以根据需要更改值 randomness.

全部放在一起:

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

输出(for Bear Bear Bear as main.txt)

Snake Bear Bear