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

如何使用Python拆分重复固定行模式的文本并生成多个独立文本文件

解决方法

核心思路

  • 先读取原始文本,对每行内容做清洗(去除首尾空格、换行符、无效空行)
  • 按每3行为1组分割清洗后的行数据,每组刚好对应用户的User、Time、Note三个属性
  • 每组数据单独写入一个独立的文本文件,文件名可以用序号或者用户名命名,避免重复

代码示例

# 1. 读取原始文本文件内容
with open("替换为你的原始文件路径.txt", "r", encoding="utf-8") as f:
    lines = f.readlines()

# 2. 清洗行数据:去掉每行首尾空白,过滤掉空行
clean_lines = []
for line in lines:
    stripped_line = line.strip()
    if stripped_line:
        clean_lines.append(stripped_line)

# 3. 按3行一组拆分,逐个写入文件
for idx in range(0, len(clean_lines), 3):
    # 取当前组的3行数据
    user_line = clean_lines[idx]
    time_line = clean_lines[idx+1]
    note_line = clean_lines[idx+2]
    # 提取用户名用于命名文件,也可以直接用序号命名
    user_name = user_line.split("=")[1].strip().replace(";", "")
    # 过滤文件名中的非法字符,避免保存失败
    user_name = user_name.replace(r"/", "").replace("\\", "").replace(":", "").replace("*", "").replace("?", "").replace('"', "").replace("<", "").replace(">", "").replace("|", "")
    # 生成当前用户的内容
    user_content = f"{user_line}\n{time_line}\n{note_line}"
    # 写入文件,无需用户名也可以用序号命名:f"用户数据_{idx//3 + 1}.txt"
    file_name = f"{user_name}_数据.txt"
    with open(file_name, "w", encoding="utf-8") as f:
        f.write(user_content)

补充说明

如果原始文本的行排列不严格对齐,中间可能夹杂多余空行或者其他内容,可以用正则匹配User=作为每组的起始标识,分组逻辑更稳定:

import re

with open("替换为你的原始文件路径.txt", "r", encoding="utf-8") as f:
    content = f.read()

# 正则匹配所有用户数据块,规则是从User=开头,到下一个User=之前的所有内容,或者到文本末尾
user_blocks = re.findall(r"User=.*?(?=User=|\Z)", content, re.DOTALL)

for block_idx, block in enumerate(user_blocks):
    # 清洗块内多余的空行和首尾空白
    cleaned_block = "\n".join([line.strip() for line in block.strip().split("\n") if line.strip()])
    with open(f"用户数据_{block_idx + 1}.txt", "w", encoding="utf-8") as f:
        f.write(cleaned_block)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 21:09:02