简体   繁体   English

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

[英]Randomly replace certain words in python using a dictionary

Does anybody know how to modify this script so that it randomly changes the words when it finds them.有谁知道如何修改这个脚本,以便它在找到单词时随机更改单词。

ie 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先感谢您

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.在上面的示例中,它将以 ~0.5 的概率将"Bear"更改为"Snake" (或 word_replacement 中的任何其他词)。 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)输出(Bear Bear Bear as main.txt)

Snake Bear Bear

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM