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")
相关推荐
测试老哥27 分钟前
Postman环境变量设置全攻略
自动化测试·软件测试·python·测试工具·职场和发展·接口测试·postman
惜月_treasure1 小时前
Text2SQL与工作流实现:让数据库查询变得轻松又高效
数据库·人工智能·python
ajassi20001 小时前
开源 Linux 服务器与中间件(四)服务器--Tomcat
linux·服务器·开源
码猩2 小时前
获取dm音视频文案
python
给我起把狙2 小时前
Django与Tornado框架深度对比:从MVCMTV到高并发架构设计
python·django·tornado
Hello.Reader2 小时前
Flink DataStream「全分区窗口处理」mapPartition / sortPartition / aggregate / reduce
大数据·python·flink
网安INF2 小时前
Python核心数据结构与函数编程
数据结构·windows·python·网络安全
列兵阿甘2 小时前
知微传感Dkam系列3D相机SDK例程篇:Python设置相机触发模式
python·数码相机·3d
wangbing11253 小时前
迁移服务器
运维·服务器
细节控菜鸡3 小时前
【排查实录】Web 页面能打开,服务器能通接口,客户端却访问失败?原因全在这!
运维·服务器·前端