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")
相关推荐
2601_962218615 分钟前
万象生鲜系统多终端统一数据协议PC手机PDA数据实时同步
大数据·数据库·人工智能·python·算法
科技苑7 分钟前
Python AI自动剪辑视频简易程序
人工智能·python
夜雪一千12 分钟前
Python爬虫实战:把Bootstrap栅格Div伪表格转为原生Table表格
python
牢姐与蒯15 分钟前
Linux进程间通信(一).进程间通信概念&&环境切换(着重强调vscode)
linux·运维·服务器·ubuntu
Web4Browser22 分钟前
浏览器指纹逆向到底在分析什么:从 JavaScript 采集、Canvas 与 WebGL 到环境一致性校验
java·服务器·前端
lqg_zone31 分钟前
CentOS 7 虚拟机磁盘 I/O 卡顿排查实录:从 iostat 异常到虚拟盘后端故障的完整定位
linux·服务器·mysql·centos
tedcloud12340 分钟前
emilkowalski/skills:让 AI 写出来的网页更有“设计感”
服务器·人工智能·开源·音视频·ai编程
Shadow(⊙o⊙)1 小时前
OTOL设计模式 One Thread One Loop
服务器·网络·设计模式
Wang's Blog1 小时前
Java 接入Redis: Redis简介与NoSQL定位
java·服务器·redis
“AI国潮设计-小江”1 小时前
【SDXL实战】Python自动化生成3D潮汕美食IP,附ComfyUI工作流与商用变现思路
开发语言·人工智能·python·prompt·aigc