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
- Broken Dictionary Building: Your loop tries to iterate over each key and its values, but you're using the entire
reqsdictionary as a key inrequirements.update({reqs: val})—that's invalid syntax, and even if you fixed it to usereqas 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. - 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. - No Index-Based Pairing: You need to match values by their position (e.g., the first
test_namewith the firstdate, firstlink1, 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
- Template Cleaning: The regex
r' --> .*?(?=( y_link |$))'finds all text starting with-->and stops just beforey_linkor the end of the string, removing those comment sections entirely. - 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 likexyz.com. - 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
相关产品推荐
相关产品推荐

