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")
相关推荐
qiudaorendao10 分钟前
作业11.9
linux·服务器·apache
wxin_VXbishe39 分钟前
springboot在线课堂教学辅助系统-计算机毕业设计源码07741
java·c++·spring boot·python·spring·django·php
岚天start1 小时前
解决方案—K8S集群的日志按天并按照命名空间分类定时同步到日志服务器
服务器·docker·kubernetes·shell·日志备份
長安只在旧夢中1 小时前
如何在Excel实现类似SQL的Where查找功能
excel·excel技巧·excel实现where
程序员三藏1 小时前
使用Docker和Selenium构建自动化测试环境
自动化测试·软件测试·python·selenium·测试工具·职场和发展·测试用例
CaracalTiger1 小时前
本地部署 Stable Diffusion3.5!cpolar让远程访问很简单!
java·linux·运维·开发语言·python·微信·stable diffusion
顾安r2 小时前
11.10 脚本算法 五子棋 「重要」
服务器·前端·javascript·游戏·flask
api_180079054602 小时前
【技术教程】Python/Node.js 调用拼多多商品详情 API 示例详解
大数据·开发语言·python·数据挖掘·node.js
0小豆02 小时前
智能字幕校准系统实战(二):6级匹配算法从精确到模糊的全链路解析
python·nlp·算法设计·spacy·ai算法·时间序列对齐
jerryinwuhan2 小时前
Python数据挖掘之回归
python·数据挖掘·回归