如何在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
相关产品推荐
相关产品推荐

