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

如何在Python中将指定格式的文本转换为列表?

如何在Python中将指定文本转换为目标嵌套列表?

输入文本与预期输出

输入文本:

input_text = """
intro: hey,how are you
i am fine

intro:
hey, how are you
Hope you are fine
"""

预期输出:

[['hey,how are you i am fine'], ['hey, how are you Hope you are fine']]

实现代码

input_text = """
intro: hey,how are you
i am fine

intro:
hey, how are you
Hope you are fine
"""

# 按空行分割文本,过滤空块
blocks = [block.strip() for block in input_text.split('\n\n') if block.strip()]

result = []
for block in blocks:
    # 拆分块内的行,过滤空行并去除首尾空白
    lines = [line.strip() for line in block.split('\n') if line.strip()]
    content_parts = []
    for line in lines:
        if line.startswith('intro:'):
            # 提取intro:后的内容,去除多余空白
            part = line[len('intro:'):].strip()
            if part:
                content_parts.append(part)
        else:
            content_parts.append(line)
    # 合并内容为单个字符串,放入子列表
    combined_content = ' '.join(content_parts)
    result.append([combined_content])

print(result)

代码说明

  • 按空行分割文本,拆分出独立的内容块,同时过滤掉无意义的空块。
  • 对每个内容块,拆分出有效行(过滤空行并去除首尾空白)。
  • 处理每行内容:如果是intro:开头的行,提取冒号后的有效内容;其他行直接保留。
  • 将每个块的所有内容片段合并为单个字符串,再嵌套进列表,最终组成符合预期的结果结构。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 22:45:40