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")
相关推荐
用户83562907805114 分钟前
Python 实现 Excel 条件格式自动化
后端·python
相偎24 分钟前
Ubuntu搭建svn服务器
服务器·ubuntu·svn
深蓝电商API1 小时前
Scrapy管道Pipeline深度解析:多方式数据持久化
爬虫·python·scrapy
噎住佩奇1 小时前
(Win11系统)搭建Python爬虫环境
爬虫·python
basketball6161 小时前
python 的对象序列化
开发语言·python
咕噜企业分发小米1 小时前
有哪些开源的直播云服务器安全防护方案?
运维·服务器·云计算
rgeshfgreh2 小时前
Python流程控制:从条件到循环实战
前端·数据库·python
luoluoal2 小时前
基于python大数据的电影市场预测分析(源码+文档)
python·mysql·django·毕业设计·源码
开开心心_Every2 小时前
安卓后台录像APP:息屏录存片段,行车用
java·服务器·前端·学习·eclipse·edge·powerpoint
幻云20102 小时前
Python深度学习:从入门到实战
人工智能·python