Python实现多替换表轮换、单词按出现顺序交替替换功能求助
实现代码
# 原始替换模板,按顺序存储三个替换规则 replace_templates = [ {'Bear': ['Black', 'Woods'], 'Duck': ['Bird', 'Feathers']}, {'Bear': ['Grizzly', 'Woods'], 'Duck': ['Quack', 'Feathers']}, {'Bear': ['Grizzly', 'Black'], 'Duck': ['Quack', 'Bird']} ] current_template_idx = 0 # 初始化当前使用的替换表,使用模板副本避免修改原始模板 current_replace = {k: v.copy() for k, v in replace_templates[current_template_idx].items()} target_words = {'Bear', 'Duck'} with open("main.txt") as main: words = main.read().split() replaced = [] for y in words: # 非目标词直接保留 if y not in target_words: replaced.append(y) continue # 当前替换表对应词的替换项已用完,轮换到下一个模板 if not current_replace[y]: current_template_idx = (current_template_idx + 1) % len(replace_templates) current_replace = {k: v.copy() for k, v in replace_templates[current_template_idx].items()} # 取出第一个元素替换,同时移除已使用的元素 replaced.append(current_replace[y].pop(0)) text = ' '.join(replaced) print(text) with open("main.txt", 'w') as new_main: new_main.write(text)
逻辑说明
- 三个替换规则统一存储为模板列表,方便按顺序循环轮换
- 每次启用新模板时都会创建独立副本,修改副本不会影响原始模板,保证每次轮换到对应模板时都有完整的2个替换项
- 遇到Bear或Duck时先检查当前模板的对应替换列表是否为空,为空就自动切换到下一个模板,三个模板用完后自动回到第一个
- 替换时使用
pop(0)方法直接取出列表第一个元素使用,同时移除该元素,符合每次用后删除的要求
内容的提问来源于stack exchange,提问作者user17026080
相关产品推荐
相关产品推荐

