You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改Python脚本实现基于替换字典的文件随机词替换功能

修改后的代码(默认50%概率替换匹配到的单词)

import random

# 单词替换映射表
word_replacement = {'Bear':'Snake', 'John':'Karen', 'Bird':'Owl'}
# 替换概率:取值范围0~1,比如0.5代表匹配到目标词时50%概率替换,50%保留原词
replace_probability = 0.5

with open("main.txt") as main:
    words = main.read().split()

replaced = []
for y in words:
    # 仅当单词在替换表中、且随机判定命中时才执行替换
    if y in word_replacement and random.random() < replace_probability:
        replaced.append(word_replacement[y])
    else:
        replaced.append(y)
text = ' '.join(replaced)

print(text)

with open("main.txt", 'w') as new_main:
    new_main.write(text)

自定义调整说明

  • 修改replace_probability的数值即可调整全局替换比例:设置为1等价于原代码的全替换逻辑,设置为0则完全不执行替换
  • 如果需要为不同单词设置独立的替换概率,可以将替换映射表调整为以下结构:
# 格式:{原词: (替换词, 对应替换概率)}
word_replacement = {
    'Bear': ('Snake', 0.6),
    'John': ('Karen', 0.3),
    'Bird': ('Owl', 0.8)
}

对应遍历逻辑调整为:

for y in words:
    if y in word_replacement:
        replace_word, prob = word_replacement[y]
        if random.random() < prob:
            replaced.append(replace_word)
            continue
    replaced.append(y)

内容的提问来源于stack exchange,提问作者user17026080

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 11:54:03