python切分文本到Excel,以包含指定字符串 为标识符(txt)切分txt文本)

V1.0_(批量处理有待完善,目前只能一个一个来)

代码如下:

bash 复制代码
import re
import openpyxl

def extract_and_save_dialogues_with_headers_to_excel(input_file, output_file):
    # 创建一个新的Excel工作簿
    workbook = openpyxl.Workbook()
    sheet = workbook.active

    # 添加行标题
    sheet.append(["说话人", "数字", "时间", "文本"])

    # 使用正则表达式来匹配说话人、数字和时间的模式
    pattern = r'说话人 (\d+) (\d+:\d+)'

    # 初始化变量以跟踪当前说话人、数字和对话文本
    current_speaker = None
    current_number = None
    current_time = None
    dialogue = []

    # 打开并读取文本文件
    with open(input_file, 'r', encoding='utf-8') as file:
        for line in file:
            match = re.match(pattern, line)
            if match:
                # 如果找到新的说话人,则保存之前的对话文本和相关信息并开始新的对话
                if current_speaker:
                    sheet.append([current_speaker, current_number, current_time, '\n'.join(dialogue)])
                    dialogue = []

                current_speaker = match.group(1)
                current_number = match.group(1)
                current_time = match.group(2)
            else:
                # 如果不是匹配到的行,则将文本行添加到当前对话中
                if current_speaker:
                    dialogue.append(line.strip())

    # 处理最后一个对话
    if current_speaker:
        sheet.append([current_speaker, current_number, current_time, '\n'.join(dialogue)])

    # 保存Excel文件
    workbook.save(output_file)

    print(f"提取并保存对话、说话人、数字、时间和文本到 {output_file} 完成")

# 使用示例
extract_and_save_dialogues_with_headers_to_excel("xu.txt", "2.xlsx")
相关推荐
哦你看看4 分钟前
学习Python 03
开发语言·windows·python
后端小张6 分钟前
[AI 学习日记] 深入解析MCP —— 从基础配置到高级应用指南
人工智能·python·ai·开源协议·mcp·智能化转型·通用协议
天青色等烟雨..9 分钟前
AI+Python驱动的无人机生态三维建模与碳储/生物量/LULC估算全流程实战技术
人工智能·python·无人机
新子y14 分钟前
【小白笔记】岛屿的周长(Island Perimeter)
笔记·python
ONE_SIX_MIX1 小时前
Debian 的 网络管理器 被意外卸载,修复过程
服务器·网络·debian
板鸭〈小号〉1 小时前
connect 的断线重连
运维·服务器
闲人编程1 小时前
深入浅出Transformer:使用Hugging Face库快速上手NLP
python·深度学习·自然语言处理·nlp·transformer·hugging face·codecapsule
wydaicls1 小时前
Linux 内核伙伴系统在快速路径分配内存时,对一个内存区域(Zone)进行水位线检查和内存压力评估的关键逻辑
linux·服务器
爬虫程序猿2 小时前
把 1688 商品详情搬进 MySQL:PHP 爬虫全链路实战(2025 版)
爬虫·python·音视频
黄昏晓x2 小时前
Linux----权限
linux·运维·服务器