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

如何批量生成仅指定单行内容不同的多份代码副本

批量替换指定字段生成多份代码副本方案

核心思路是用固定模板标记唯一待替换位置,遍历名称列表逐次替换生成副本,完全不会改动其余代码内容,具体操作如下:

  • 准备基础文件
    1. 新建names.txt存储名称列表,每行写一个待替换的名称,格式参考:
    Jay
    Joy
    Jane
    Juda
    
    1. 新建template.txt存储代码模板,找到你需要修改的那一处名称,替换成不会和代码其他内容冲突的固定占位符(比如{{TARGET_NAME}}),其余内容原封不动保留,参考示例:
    print("Hi");
    Print("Hello")
    print("{{TARGET_NAME}}"); # here
    
  • 批量生成脚本,选你能用的即可,不用额外装复杂工具
    ① Windows系统自带PowerShell方案:
    新建gen.ps1和上面两个文件放在同一文件夹,写入以下内容,右键选择「使用PowerShell运行」,最终结果会自动生成到同目录的output.txt里:
    $template = Get-Content .\template.txt -Raw
    $names = Get-Content .\names.txt | Where-Object { $_.Trim() -ne "" }
    $result = @()
    foreach ($name in $names) {
        $result += $template -replace "{{TARGET_NAME}}", $name.Trim()
    }
    $result -join "`r`n`r`n" | Out-File .\output.txt -Encoding utf8
    
    ② 跨平台Python方案(Windows/Mac/Linux通用,有Python环境就能用):
    新建gen.py和上面两个文件放在同一文件夹,写入以下内容,在当前目录执行python gen.py即可生成output.txt:
    with open("template.txt", "r", encoding="utf-8") as f:
        template = f.read()
    
    with open("names.txt", "r", encoding="utf-8") as f:
        names = [line.strip() for line in f if line.strip()]
    
    output_sections = []
    for name in names:
        output_sections.append(template.replace("{{TARGET_NAME}}", name))
    
    with open("output.txt", "w", encoding="utf-8") as f:
        f.write("\n\n".join(output_sections))
    

避坑提醒:不要直接对原始代码做全局字符串替换,万一代码其他位置出现和待替换名称相同的字符串就会被误改。用占位符单独标记唯一待修改位置,能保证除了你指定的字段,其余代码内容、格式、注释完全和原模板一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 07:15:56