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

Python实现字典多组值批量替换模板文件占位符失败的技术求助

Fixing Your Template Replacement Code

Let's walk through what's broken in your current code and build a working solution that matches your expected output.

What's Wrong With Your Current Implementation

  1. Broken Dictionary Building: Your loop tries to iterate over each key and its values, but you're using the entire reqs dictionary as a key in requirements.update({reqs: val})—that's invalid syntax, and even if you fixed it to use req as the key, you'd overwrite each key's value every time, leaving you with only the last value for each key instead of grouping values by their index.
  2. Ignoring Template Comments: The original template has --> replace with ... notes that aren't in your expected output, so we need to strip those out first.
  3. No Index-Based Pairing: You need to match values by their position (e.g., the first test_name with the first date, first link1, etc.), not process each key's values independently.

Correct Solution Code

First, let's define your data and fix the template handling:

# Your original data dictionary
reqs = {
    'test_name': ['D S', 'C S'],
    'date': ['23/04/2021', '02/05/2021'],
    'link1': ['smk.com', 'xyz.com '],
    'link2': ['pst.com', 'abc.com ']
}

# Read and clean the template file: remove the --> comment sections
with open('file.txt', 'r') as template_file:
    raw_template = template_file.read()

# Use regex to strip out the --> comments without affecting the rest of the text
import re
clean_template = re.sub(r' --> .*?(?=( y_link |$))', '', raw_template)

# Iterate over each index to generate the output
num_iterations = len(next(iter(reqs.values())))  # Get count from first list's length

for iteration_num in range(num_iterations):
    # Build a dictionary for this iteration: map each key to its index-matched value
    current_data = {
        key: reqs[key][iteration_num].strip()  # Strip trailing spaces from links
        for key in reqs
    }
    # Format the template with current iteration's data
    output = clean_template.format(**current_data)
    
    # Print in your desired format
    print(f"迭代{iteration_num + 1}:")
    print(f"```\n{output}\n```")

How This Works

  1. Template Cleaning: The regex r' --> .*?(?=( y_link |$))' finds all text starting with --> and stops just before y_link or the end of the string, removing those comment sections entirely.
  2. Index-Based Data Mapping: For each iteration, we create a temporary dictionary that pairs each placeholder key with the value at the current index in its list. We use .strip() to clean up trailing spaces in links like xyz.com .
  3. Template Formatting: Using Python's str.format(**current_data) replaces each {placeholder} in the cleaned template with the corresponding value from the temporary dictionary.

Expected Output

When you run this code, you'll get exactly the output you wanted:
迭代1:

Pending of taking test D S was due on 23/04/2021. Follow the below link X_link : smk.com y_link : pst.com

迭代2:

Pending of taking test C S was due on 02/05/2021. Follow the below link X_link : xyz.com y_link : abc.com

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 15:27:40