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

如何用/n和:双分隔符拆分字符串生成键值对结构?

字符串转键值对的Pythonic实现方案

问题说明

输入字符串(注意原输入中的/n应为换行符\n,以下按正确格式处理):

Text1:\nText\nText2:\nText\nText\nText3:\nText

需要将其转换为键值对结构:带:的行作为键,后续不带:的行合并为对应值(换行替换为空格),期望输出:

{"Text1":"Text","Text2":"Text Text","Text3":"Text"}

最终结果需支持存入大型DataFrame,不局限于字典结构。

尝试的无效代码

你之前尝试的字典推导式无法正确匹配键值关系:

infodict = {k+1: v for k, v in enumerate(infostr.split(":"))}

解决方案

方法1:正则表达式(简洁高效)

利用正则一次性匹配所有键值对,适合处理结构化的文本:

import re

infostr = "Text1:\nText\nText2:\nText\nText\nText3:\nText"
# 正则模式:匹配键([^:\n]+):,然后匹配后续内容直到下一个键或结尾
pattern = r"([^:\n]+):\s*(.*?)(?=\n[^:\n]+:|$)"
matches = re.findall(pattern, infostr, re.DOTALL)

# 整理字典,将值中的换行替换为空格
result_dict = {key: value.replace("\n", " ").strip() for key, value in matches}
print(result_dict)
# 输出: {'Text1': 'Text', 'Text2': 'Text Text', 'Text3': 'Text'}

方法2:逐行遍历(直观易维护)

通过遍历分割后的行,手动收集键和对应值,适合需要自定义逻辑的场景:

infostr = "Text1:\nText\nText2:\nText\nText\nText3:\nText"
# 分割行并过滤空行
lines = [line.strip() for line in infostr.split("\n") if line.strip()]

result_dict = {}
current_key = None
current_value = []

for line in lines:
    if ":" in line:
        # 保存上一个键值对(如果存在)
        if current_key is not None:
            result_dict[current_key] = " ".join(current_value)
        # 提取当前键(去掉末尾的冒号)
        current_key = line.rstrip(":")
        current_value = []
    else:
        # 收集值的行
        current_value.append(line)
# 处理最后一组键值对
if current_key is not None:
    result_dict[current_key] = " ".join(current_value)

print(result_dict)
# 输出: {'Text1': 'Text', 'Text2': 'Text Text', 'Text3': 'Text'}

转换为DataFrame

如果要存入大型DataFrame,可直接将结果转换:

import pandas as pd

# 从字典转换
df = pd.DataFrame.from_dict(result_dict, orient="index", columns=["value"]).reset_index().rename(columns={"index": "key"})

# 或从正则匹配结果直接构建
df = pd.DataFrame(matches, columns=["key", "value"])
df["value"] = df["value"].str.replace("\n", " ").str.strip()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 06:46:19