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")
相关推荐
Stara051143 分钟前
基于多头自注意力机制(MHSA)增强的YOLOv11主干网络—面向高精度目标检测的结构创新与性能优化
人工智能·python·深度学习·神经网络·目标检测·计算机视觉·yolov11
那雨倾城2 小时前
使用 OpenCV 将图像中标记特定颜色区域
人工智能·python·opencv·计算机视觉·视觉检测
LuckyTHP4 小时前
java 使用zxing生成条形码(可自定义文字位置、边框样式)
java·开发语言·python
热河暖男4 小时前
【实战解决方案】Spring Boot+Redisson构建高并发Excel导出服务,彻底解决系统阻塞难题
spring boot·后端·excel
厦门辰迈智慧科技有限公司5 小时前
城市排水管网流量监测系统解决方案
运维·服务器
mahuifa6 小时前
(7)python开发经验
python·qt·pyside6·开发经验
国际云,接待7 小时前
云服务器的运用自如
服务器·架构·云计算·腾讯云·量子计算
学地理的小胖砸7 小时前
【Python 操作 MySQL 数据库】
数据库·python·mysql
安迪小宝7 小时前
6 任务路由与负载均衡
运维·python·celery
Blossom.1187 小时前
使用Python实现简单的人工智能聊天机器人
开发语言·人工智能·python·低代码·数据挖掘·机器人·云计算