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

如何修改Python脚本实现每遇到关键词rat就切换替换字典?

Python脚本修改方案

修改要点

  • 修复原脚本语法错误:原脚本直接对列表类型的word_replacement调用字典专属的get()方法,运行会直接报错
  • 新增索引变量跟踪当前使用的替换字典,初始值为0
  • 每次处理完单词rat之后,自动切换到下一个替换字典,索引超过列表长度时默认自动从第一个字典重新开始
  • 优化写文件逻辑,改用上下文管理器自动管理文件句柄,避免手动关闭文件遗漏导致的资源泄漏

完整修改后代码

word_replacement = [{'dog': 'Bob', 'cat': 'Sally', 'bird': 'John', 'rat': 'Pat'},
        {'dog': 'Brown', 'cat': 'White', 'bird': 'Black', 'rat': 'Grey'},
        {'dog': 'Bark', 'cat': 'Meow', 'bird': 'Chirp', 'rat': 'Squeek'}]

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

replaced = []
current_dict_idx = 0
replacement_total = len(word_replacement)

for word in words:
    # 取当前字典做替换
    current_replacer = word_replacement[current_dict_idx]
    replaced_word = current_replacer.get(word, word)
    replaced.append(replaced_word)
    # 遇到rat就切换下一个字典
    if word == 'rat':
        current_dict_idx = (current_dict_idx + 1) % replacement_total

result_text = ' '.join(replaced)
print(result_text)

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

适配调整说明

  • 如果你不需要循环使用替换字典,超出列表长度后固定使用最后一个字典,可将切换索引的代码替换为如下逻辑:
if current_dict_idx < replacement_total - 1:
    current_dict_idx += 1

验证结果

你提供的示例输入dog bird rat dog cat cat rat bird rat cat dog运行后,输出和期望结果完全一致:
Bob John Pat Brown White White Grey Chirp Squeek Sally Bob

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 12:06:03