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

Python如何从含花括号的字符串中提取指定结构的字典?

提取字符串中的花括号占位符生成字典

当然可以实现,核心思路是用正则表达式匹配字符串中的花括号占位符,再生成符合要求的字典结构,后续配合str.format()完成填充。

1. 提取占位符生成字典

用re.findall()匹配花括号内的标识符,再通过字典推导式生成目标字典:

import re

def get_placeholder_dict(text):
    # 匹配花括号内的字母/数字/下划线(可根据需求调整正则规则)
    placeholder_keys = re.findall(r'{(\w+)}', text)
    # 生成键对应空字典的结构
    return {key: {} for key in placeholder_keys}

测试示例:

sample_text = 'my name is {name}'
result = get_placeholder_dict(sample_text)
print(result)  # 输出: {'name': {}}

2. 配合format填充内容

拿到字典后,只需为键赋值,再用**解包字典传入format():

result['name'] = 'Alice'
filled_text = sample_text.format(**result)
print(filled_text)  # 输出: 'my name is Alice'

3. 处理文本文件的完整流程

针对你读取模板文件、填充后写回的需求,完整代码示例如下:

import re

def get_placeholder_dict(text):
    placeholder_keys = re.findall(r'{(\w+)}', text)
    return {key: {} for key in placeholder_keys}

# 1. 读取模板文件
with open('template.txt', 'r', encoding='utf-8') as f:
    template_content = f.read()

# 2. 提取占位符字典
placeholders = get_placeholder_dict(template_content)

# 3. 为占位符赋值(可根据业务逻辑动态生成值)
placeholders['name'] = 'Bob'
placeholders['city'] = 'New York'

# 4. 填充文本并写回文件
filled_content = template_content.format(**placeholders)
with open('filled_template.txt', 'w', encoding='utf-8') as f:
    f.write(filled_content)

扩展说明

  • 如果你的占位符包含特殊字符(比如{user.email}这种带点的格式),可以把正则调整为r'{([\w.]+)}'来匹配;
  • 字典推导式会自动去重重复的占位符,避免字典键冲突。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 11:47:42