如何用Python将垂直文本转换为横向CSV格式
问题:将按Statement分组的文本转为横向CSV文件
现有文本文件以Statement开头的行作为分组标记,每组行数不固定。需求是提取每个分组(从当前Statement行到下一个Statement行之前的所有内容),将这些分组横向排列为逗号分隔的CSV文件。
输入示例
Statement 1 some text some text some text some text some text some text some text Statement 2 some text some text some text some text some text some text Statement 3 some text some text some text some text some text some text some text some text some text some text some text Statement 4 some text some text some text some text some text some text some text some text
输出示例
Statement 1,Statement 2,Statement 3,Statement 4 some text,some text,some text,some text some text,some text,some text,some text some text,some text,some text,some text some text,some text,some text,some text some text,some text,some text,some text some text,some text,some text,some text some text,,some text,some text ,,some text,some text ,,some text, ,,some text, ,,some text,
实现代码
def convert_to_horizontal_csv(input_path, output_path): # 1. 读取文件并按Statement分组 groups = [] current_group = [] with open(input_path, 'r', encoding='utf-8') as f: for line in f: line = line.rstrip('\n') # 保留行内空白,仅去除换行符 if line.startswith('Statement'): if current_group: groups.append(current_group) current_group = [line] else: if current_group: current_group.append(line) # 处理最后一个分组 if current_group: groups.append(current_group) # 2. 确定最长分组的行数,补全短分组的空缺 max_line_count = max(len(group) for group in groups) # 3. 生成横向CSV并写入文件 with open(output_path, 'w', encoding='utf-8') as f: for idx in range(max_line_count): row_items = [] for group in groups: row_items.append(group[idx] if idx < len(group) else '') f.write(','.join(row_items) + '\n') # 调用函数,替换为你的文件路径 convert_to_horizontal_csv('input_text_file.txt', 'output_csv_file.csv')
代码说明
- 分组逻辑:遍历文件每行,遇到
Statement开头的行时,将当前收集的分组存入列表并新建分组;非Statement行则追加到当前分组。 - 空缺补全:找到所有分组中最长的行数,确保每行能对应所有分组的内容,短分组不足的位置用空字符串填充。
- CSV生成:逐行提取每个分组的对应行内容,用逗号拼接成一行后写入文件,实现横向排列效果。
内容的提问来源于stack exchange,提问作者new_py
相关产品推荐
相关产品推荐

