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



有人知道如何修改这个脚本,使它随机改变单词时,它找到他们。

。并不是每一个"熊"的例子。成为"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()

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

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

在上面的示例中,它将以~0.5的概率将"Bear"更改为"Snake"(或word_replacement中的任何其他单词)。您可以将值更改为您想要的随机性

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)

(for Bear Bear as main.txt)

Snake Bear Bear