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

Python如何逐行读取字符串 基于字典实现同词差异化随机替换

问题描述

我正在尝试使用字典实现字符串替换功能。
基于字典做替换的实现逻辑本身很简单,但如果将所有匹配的同一单词全部替换为同一个值,最终生成的语句会十分生硬。
我尝试逐行读取文本、逐行执行替换操作,但代码运行未达到预期效果,原有代码如下:

# A function that randomly replaces a word
def ttc(*arg):
    a = random.choice([*arg])
    return ''.join(a)

text = """
I'm working on replacing a string using a dictionary.

I'm working on replacing a string using a dictionary.

I'm working on replacing a string using a dictionary.
I'm working on replacing a string using a dictionary.

I'm working on replacing a string using a dictionary.
I'm working on replacing a string using a dictionary.

"""
a_dic = {'working': ttc('tttttt', 'yyyyy', 'iiiiii'),
         'using': ttc('qqqq', 'eeeee', 'rrrrrr'),
         'on': ttc('cdcd', 'vvvdvdvv', 'dvd')
         }

new_list = []
pos = -1
for s in text.split("\n"):
    pos += 1
    if s == "":
        new_list.append(s)
    else:
        for key in a_dic.keys():
            s = s.replace(key, a_dic[key])
            if pos == len(a_dic) - 1:
                new_list.append(s)


for d in new_list:
    print(d)

我需要实现的效果是:文本中多处出现的同一个单词,每次匹配到都替换为不同的随机值,而非所有位置统一替换成同一个固定值,预期输出参考如下:

text = """
I'm tttttt dvd replacing a string eeeee a dictionary.

I'm yyyyy cdcd replacing a string qqqq a dictionary.

I'm tttttt cdcd replacing a string qqqq a dictionary.
I'm tttttt vvvdvdvv replacing a string eeeee a dictionary.

I'm iiiiii cdcd replacing a string rrrrrr a dictionary.
I'm iiiiii vvvdvdvv replacing a string qqqq a dictionary.

"""
问题原因

原有代码存在两个核心问题:

  1. 字典a_dic初始化阶段就调用了ttc()函数,每个key对应的value是提前生成的固定随机值,并非每次匹配到单词时才生成新值,因此所有匹配位置都会被替换为同一个固定内容。
  2. 逐行替换的内容追加逻辑有误,会重复生成无效内容,且整行全局替换的逻辑无法支持同个单词在同一句子的不同位置取不同随机值。
实现方案

使用正则表达式的替换回调功能,每次匹配到目标单词时,实时调用随机选择逻辑生成替换值,即可实现每处匹配单独随机的效果,可运行代码如下:

import random
import re

text = """
I'm working on replacing a string using a dictionary.

I'm working on replacing a string using a dictionary.

I'm working on replacing a string using a dictionary.
I'm working on replacing a string using a dictionary.

I'm working on replacing a string using a dictionary.
I'm working on replacing a string using a dictionary.

"""
# 字典存储每个待替换词对应的可选替换值列表,不提前生成固定随机值
replace_map = {
    'working': ['tttttt', 'yyyyy', 'iiiiii'],
    'using': ['qqqq', 'eeeee', 'rrrrrr'],
    'on': ['cdcd', 'vvvdvdvv', 'dvd']
}

# 构建匹配所有目标词的正则,自动转义避免特殊字符匹配异常
pattern = re.compile('|'.join(re.escape(k) for k in replace_map.keys()))

# 每次匹配到词时,实时从对应可选列表随机选值返回
def replace_match(match):
    word = match.group(0)
    return random.choice(replace_map[word])

# 执行全文替换
result = pattern.sub(replace_match, text)

print(result)

方案说明

  • 替换字典不再提前调用随机函数生成固定值,而是存储每个单词对应的所有可选替换值列表
  • 用正则一次性匹配所有需要替换的单词,每匹配到一处就触发一次回调函数,实时随机选择替换内容,保证每处匹配的替换值互相独立
  • 不需要手动逐行拆分、循环替换,正则替换会自动处理全文本的所有匹配位置,也不会出现重复追加行的问题
  • 如果需要做整词匹配(避免替换到长单词里的子串,比如把only里的on误替换),可以把正则pattern修改为re.compile(r'\b(' + '|'.join(re.escape(k) for k in replace_map.keys()) + r')\b')即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 19:39:17