AI办公自动化:用kimi批量把word转换成txt文本

在Kimichat中输入提示词:

你是一个Python编程专家,要完成一个Python脚本编写的任务,具体步骤如下:

打开文件夹:F:\aword

读取里面docx格式的word文档,

提取word文档中的第一行文字作为txt文本文档的标题名,

将word文档转换为txt文档;

重命名txt文档;

注意:每一步相关信息都要输出到屏幕;

在 Windows 系统中,默认的文件编码是 GBK,它不支持某些特殊的 Unicode 字符,为了解决这个问题,可以在打开文件进行写入操作时,指定使用 utf-8 编码

kimichat生成Python源代码:

import os

from docx import Document

定义文件夹路径

folder_path = 'F:\\aword'

确保文件夹存在

if not os.path.exists(folder_path):

print(f"文件夹 {folder_path} 不存在。")

else:

列出文件夹中所有的docx文件

docx_files = [f for f in os.listdir(folder_path) if f.endswith('.docx')]

检查是否有docx文件

if not docx_files:

print("没有找到docx格式的Word文档。")

else:

for docx_file in docx_files:

构建完整的文件路径

docx_file_path = os.path.join(folder_path, docx_file)

读取Word文档

doc = Document(docx_file_path)

try:

提取第一行文字作为标题

title = doc.paragraphs[0].text.strip()

print(f"提取的标题为: {title}")

构建txt文件的完整路径

txt_file_path = os.path.join(folder_path, f"{title}.txt")

将Word文档转换为txt

with open(txt_file_path, 'w', encoding='utf-8') as txt_file:

for para in doc.paragraphs:

txt_file.write(para.text + '\n')

print(f"文档 {docx_file} 已转换为txt格式。")

except IndexError:

print(f"文档 {docx_file} 中没有文本。")

except Exception as e:

print(f"处理文档 {docx_file} 时发生错误: {e}")

在vscode中运行源代码,成功。

相关推荐
追逐时光者4 小时前
一个致力于为 C# 程序员提供更佳的编码体验和效率的 Visual Studio 扩展插件
后端·c#·visual studio
molaifeng5 小时前
Go 语言如何实现高性能网络 I/O:Netpoller 模型揭秘
开发语言·网络·golang
崇山峻岭之间5 小时前
Matlab学习记录33
开发语言·学习·matlab
Evand J5 小时前
【2026课题推荐】DOA定位——MUSIC算法进行多传感器协同目标定位。附MATLAB例程运行结果
开发语言·算法·matlab
jllllyuz6 小时前
基于MATLAB的二维波场模拟程序(含PML边界条件)
开发语言·matlab
忆锦紫6 小时前
图像增强算法:Gamma映射算法及MATLAB实现
开发语言·算法·matlab
SunflowerCoder6 小时前
EF Core + PostgreSQL 配置表设计踩坑记录:从 23505 到 ChangeTracker 冲突
数据库·postgresql·c#·efcore
亲爱的非洲野猪7 小时前
Java锁机制八股文
java·开发语言
LawrenceLan7 小时前
Flutter 零基础入门(十二):枚举(enum)与状态管理的第一步
开发语言·前端·flutter·dart
charlie1145141918 小时前
从 0 开始的机器学习——NumPy 线性代数部分
开发语言·人工智能·学习·线性代数·算法·机器学习·numpy