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

Python将多行结构化文本转换为字典的实现方案咨询

如何将INI风格文本转换为键-值块字典?

方案1:生成「键: 值文本块」字典

如果你只需要把每个键对应的所有值行存成一个文本块,方便后续用startswith()查找特定值,可以用以下代码:

config_dict = {}
current_key = None

# 替换成你的文件路径
with open('config.txt', 'r', encoding='utf-8') as f:
    for line in f:
        # 去除首尾空白字符(包括换行符)
        cleaned_line = line.strip()
        # 跳过空行(处理松散结构的空白行)
        if not cleaned_line:
            continue
        # 识别[Key]格式的行,提取键名
        if cleaned_line.startswith('[') and cleaned_line.endswith(']'):
            current_key = cleaned_line[1:-1]
            # 为当前键初始化空的文本块
            config_dict[current_key] = ''
        # 如果已经定位到当前键,将值行追加到文本块(保留换行)
        elif current_key is not None:
            config_dict[current_key] += cleaned_line + '\n'

使用示例

比如要提取ThisShouldBeAKey下的Value2:

target_key = 'ThisShouldBeAKey'
target_value_name = 'Value2'

# 拆分文本块为逐行遍历
for line in config_dict[target_key].splitlines():
    if line.startswith(f'{target_value_name}='):
        # 分割出值(只分割一次,避免值里包含等号)
        value = line.split('=', 1)[1]
        print(f'{target_value_name}: {value}')
        break

方案2:生成嵌套字典(更适合直接对比值)

如果需要直接获取某个键下的特定值(比如对比Key1.Value8和Key100.Value9),用嵌套字典会更高效:

config_dict = {}
current_key = None

with open('config.txt', 'r', encoding='utf-8') as f:
    for line in f:
        cleaned_line = line.strip()
        if not cleaned_line:
            continue
        if cleaned_line.startswith('[') and cleaned_line.endswith(']'):
            current_key = cleaned_line[1:-1]
            # 为当前键初始化嵌套字典,存具体的Value键值对
            config_dict[current_key] = {}
        # 处理Value=xxx格式的行,分割键值对
        elif current_key is not None and '=' in cleaned_line:
            # maxsplit=1确保值里的等号不会被分割
            val_name, val_content = cleaned_line.split('=', 1)
            config_dict[current_key][val_name.strip()] = val_content.strip()

使用示例

直接通过键路径获取值并对比:

# 获取目标值,用get()避免键不存在时报错
key1_val8 = config_dict.get('Key1', {}).get('Value8', '未找到该值')
key100_val9 = config_dict.get('Key100', {}).get('Value9', '未找到该值')

print(f'Key1.Value8: {key1_val8}')
print(f'Key100.Value9: {key100_val9}')
print(f'是否相等: {key1_val8 == key100_val9}')

注意事项

  • 如果你的文件里有注释行(比如以#或;开头),可以在跳过空行的逻辑后加判断:if cleaned_line.startswith(('#', ';')): continue来跳过注释。
  • 对于值里包含等号的情况,代码中用split('=', 1)只分割一次,能保证值的完整性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 02:13:35