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

相关推荐
蜡笔小鑫jolly4 分钟前
在WORD中插入表格后放图片一直不吻合怎么办?
word
期待のcode20 分钟前
java的IO流
java·开发语言
w-w0w-w20 分钟前
C++泛型编程
开发语言·c++·算法
YJlio22 分钟前
PsPing 学习笔记(14.8):常见错误与排障实战(超时、拒绝连接、权限问题)
开发语言·笔记·python·学习·django·pdf·pygame
LegendNoTitle28 分钟前
Windows和Linux下Rust-init、Cargo下载慢的解决
开发语言·windows·rust
亓才孓33 分钟前
深浅拷贝--Java
java·开发语言·windows
潲爺37 分钟前
Java笔记总结
java·开发语言·笔记·学习
菜的不敢吱声39 分钟前
swift学习第一天
开发语言·学习·swift
培林将军42 分钟前
C语言指针
c语言·开发语言·算法
云栖梦泽44 分钟前
鸿蒙分布式应用全链路性能调优实战
开发语言·鸿蒙系统