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中运行源代码,成功。

相关推荐
Joey_friends40 分钟前
【Linux】线程详解
开发语言
_GR1 小时前
Qt开发⑧Qt的窗口_下_浮动窗口+对话框
开发语言·css·c++·qt·microsoft
Good Note1 小时前
Golang——常用库context和runtime
开发语言·爬虫·golang
清河__1 小时前
【Go】十七、grpc 服务的具体功能编写
开发语言·后端·golang
张声录12 小时前
国密算法Sm2工具类--golang实现版
开发语言·后端·golang
HH牛码2 小时前
C# 中 Array、ArrayList 和 List 的比较
开发语言·c#
HH牛码2 小时前
C#学生管理系统 进阶(通过接口,继承接口的类,实现接口约束_对List中存储的数据进行排列)
c#
吾与谁归in3 小时前
C#实现本地Deepseek模型及其他模型的对话
人工智能·c#·wpf·deepseek
zr想努力3 小时前
Lua的table类型的增删改查操作
java·开发语言·lua
快乐点吧3 小时前
【word】保存重开题注/交叉引用消失,更新域问题
word