AI神助攻!小白也能制作自动重命名工具~

我们平时从网上下载一些文件,文件名很多都是一大串字母和数字,不打开看看,根本不知道里面是什么内容。

在这里插入图片描述

我想能不能做个工具,把我们一个文件夹下面的所有word、excel、ppt、pdf文件重命名为文件内容的第一行。

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

我们有些朋友可能不会编程,别慌,不会编程也没关系,我们可以让AI帮我们写一个Python程序。

下面我就让Kimi帮我们写一个程序:

在这里插入图片描述

我把上面这段代码复制到vscode中,把‘path_to_your_directory’替换成自己的文件夹路径,直接运行一下。

在这里插入图片描述

很不幸,报错了,没事,把错误提示复制出来,继续问Kimi:

在这里插入图片描述

再报错,再问:

在这里插入图片描述

你就不厌其烦的问。

AI的一个好处是他永远不会发脾气,哈哈,你只管问就行,不管你的问题有多白痴,它总是会耐心回答,也不会笑话你,这点AI比人类要强百倍。

最终AI给出了一个可运行的版本:

import os
from docx import Document
from openpyxl import load_workbook
from pptx import Presentation
from pdfminer.high_level import extract_textdef get_first_line_from_word(file_path):try:doc = Document(file_path)return doc.paragraphs[0].text if doc.paragraphs else ''except Exception as e:print(f"Error reading Word file {file_path}: {e}")return ''def get_first_line_from_excel(file_path):try:wb = load_workbook(file_path)sheet = wb.activefor row in sheet.iter_rows(min_row=1, values_only=True):for value in row:if value is not None:return str(value)return ''except Exception as e:print(f"Error reading Excel file {file_path}: {e}")return ''def get_first_line_from_ppt(file_path):try:presentation = Presentation(file_path)for slide in presentation.slides:for shape in slide.shapes:if hasattr(shape, 'text') and shape.text:return shape.text[:shape.text.index('\n')] if '\n' in shape.text else shape.textreturn ''except Exception as e:print(f"Error reading PPT file {file_path}: {e}")return ''def get_first_line_from_pdf(file_path):try:text = extract_text(file_path)return text.split('\n', 1)[0] if text else ''except Exception as e:print(f"Error reading PDF file {file_path}: {e}")return ''def rename_files(directory):for filename in os.listdir(directory):if filename.lower().endswith(('.docx', '.xlsx', '.pptx', '.pdf')) and not filename.lower().startswith('.~') :file_path = os.path.join(directory, filename)first_line = ''if filename.lower().endswith('.docx'):first_line = get_first_line_from_word(file_path)elif filename.lower().endswith('.xlsx'):first_line = get_first_line_from_excel(file_path)elif filename.lower().endswith('.pptx'):first_line = get_first_line_from_ppt(file_path)elif filename.lower().endswith('.pdf'):first_line = get_first_line_from_pdf(file_path)if first_line:new_filename = first_line.strip() + os.path.splitext(filename)[1]new_file_path = os.path.join(directory, new_filename)os.rename(file_path, new_file_path)print(f"Renamed {filename} to {new_filename}")else:print(f"No first line found for {filename}")# Specify the directory containing the files
directory = '/Users/zhan/Documents/test'  # Replace with the path to your directory
rename_files(directory)

运行效果如下:

在这里插入图片描述

我们还需要一个UI界面,让我们可以在图形界面上操作,我们继续问Kimi:

在这里插入图片描述
最终代码如下:

import os
from docx import Document
from openpyxl import load_workbook
from pptx import Presentation
from pdfminer.high_level import extract_text
import tkinter as tk
from tkinter import filedialog, messagebox
from tkinter import ttkdef get_first_line_from_word(file_path):try:doc = Document(file_path)return doc.paragraphs[0].text if doc.paragraphs else ''except Exception as e:print(f"Error reading Word file {file_path}: {e}")return ''def get_first_line_from_excel(file_path):try:wb = load_workbook(file_path)sheet = wb.activefor row in sheet.iter_rows(min_row=1, values_only=True):for value in row:if value is not None:return str(value)return ''except Exception as e:print(f"Error reading Excel file {file_path}: {e}")return ''def get_first_line_from_ppt(file_path):try:presentation = Presentation(file_path)for slide in presentation.slides:for shape in slide.shapes:if hasattr(shape, 'text') and shape.text:return shape.text[:shape.text.index('\n')] if '\n' in shape.text else shape.textreturn ''except Exception as e:print(f"Error reading PPT file {file_path}: {e}")return ''def get_first_line_from_pdf(file_path):try:text = extract_text(file_path)return text.split('\n', 1)[0] if text else ''except Exception as e:print(f"Error reading PDF file {file_path}: {e}")return ''def rename_files(directory):for filename in os.listdir(directory):if filename.lower().endswith(('.docx', '.xlsx', '.pptx', '.pdf')) and not filename.lower().startswith('.~') :file_path = os.path.join(directory, filename)first_line = ''if filename.lower().endswith('.docx'):first_line = get_first_line_from_word(file_path)elif filename.lower().endswith('.xlsx'):first_line = get_first_line_from_excel(file_path)elif filename.lower().endswith('.pptx'):first_line = get_first_line_from_ppt(file_path)elif filename.lower().endswith('.pdf'):first_line = get_first_line_from_pdf(file_path)if first_line:new_filename = first_line.strip() + os.path.splitext(filename)[1]new_file_path = os.path.join(directory, new_filename)os.rename(file_path, new_file_path)print(f"Renamed {filename} to {new_filename}")else:print(f"No first line found for {filename}")# Specify the directory containing the files
directory = '/Users/zhan/Documents/test'  # Replace with the path to your directory      # 这里是之前定义的rename_files函数和子函数
def choose_directory():directory = filedialog.askdirectory()if directory:entry.delete(0, tk.END)entry.insert(0, directory)def rename_files_with_ui():directory = entry.get()if not directory:messagebox.showerror("错误", "请选择一个文件夹")returnif not os.path.isdir(directory):messagebox.showerror("错误", "所选路径不是一个文件夹")returntry:rename_files(directory)messagebox.showinfo("完成", "文件重命名完成")except Exception as e:messagebox.showerror("错误", f"发生错误: {e}")# 创建主窗口
root = tk.Tk()
root.title("文件批量重命名工具")# 创建一个标签和输入框用于显示选择的文件夹路径
label = ttk.Label(root, text="请选择文件夹:")
label.pack()
entry = tk.Entry(root, width=30)
entry.pack()# 创建一个按钮,点击时弹出选择文件夹的对话框
browse_button = ttk.Button(root, text="浏览", command=choose_directory)
browse_button.pack()# 创建一个按钮,点击时执行重命名操作
rename_button = ttk.Button(root, text="确定", command=rename_files_with_ui)
rename_button.pack()# 设置窗口的尺寸
width = 350  # 宽度
height = 200  # 高度# 获取屏幕的宽度和高度
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()# 计算窗口的中心坐标
x = (screen_width / 2) - (width / 2)
y = (screen_height / 2) - (height / 2)# 将窗口放置在屏幕中心
root.geometry(f'{width}x{height}+{int(x)}+{int(y)}')# 运行主循环
root.mainloop()

我们看下运行效果:

在这里插入图片描述

试了一下,功能和上面的程序是一样的。

最后一步就是打包程序了,同样我们问下AI:

在这里插入图片描述
一共就两步:

  1. 安装PyInstaller
pip install pyinstaller
  1. 使用PyInstaller打包
pyinstaller --onefile --windowed file_renamer_gui.py

注意要把“file_renamer_gui.py"替换成你自己的文件名。

打包好之后,在项目目录的dist文件夹下就可以找到打包好的文件。

在这里插入图片描述

双击打开即可运行,效果是一样的。

在这里插入图片描述

好了,这个工具就写好了。

有了AI的助攻,我们想写什么工具直接让AI帮我们写就好了,是不是给了你很大的信心?

原来编程也不难,编程我也会啊~

上面的代码亲测可用,如果你想直接下载exe文件,关注公众号“编程我也会”,回复“重命名”即可下载。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/670478.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

基于51单片机8位竞赛抢答器—倒计时可调

基于51单片机8路抢答器 (仿真+程序+设计报告) 功能介绍 具体功能: 1.主持人按键控制开始抢答; 2.开始前主持人可以设定抢答时间; 3.开始抢答后,数码管开始倒计时,第一…

video标签,如何隐藏右下角三个点包含的功能?

// nodownload: 不要下载 // nofullscreen: 不要全屏 // noremoteplayback: 不要远程回放 // disablePictureInPicture: 不要画中画 <videocontrols disablePictureInPicture"true"controlslist"nodownload nofullscreen noremoteplayback" > </v…

Django高级表单处理与验证实战

title: Django高级表单处理与验证实战 date: 2024/5/6 20:47:15 updated: 2024/5/6 20:47:15 categories: 后端开发 tags: Django表单验证逻辑模板渲染安全措施表单测试重定向管理最佳实践 引言&#xff1a; 在Web应用开发中&#xff0c;表单是用户与应用之间进行交互的重要…

AI预测福彩3D第10套算法实战化赚米验证第2弹2024年5月6日第2次测试

由于今天白天事情比较多&#xff0c;回来比较晚了&#xff0c;趁着还未开奖&#xff0c;赶紧把预测结果发出来吧~今天是第2次测试~ 2024年5月6日福彩3D预测结果 6-7码定位方案如下&#xff1a; 百位&#xff1a;3、4、1、7、8、9 十位&#xff1a;4、5、3、7、8、9 个位&#x…

git使用注意事项事项

以下操作均在gitee平台上实现 文章目录 1、本地仓库和远程仓库有冲突2、git提交自动忽略某些文件3、git无法push提交到远程仓库 1、本地仓库和远程仓库有冲突 在web端修改了文件内容或者删除了文件&#xff0c;本地仓库需要重新把远程仓库拉取到本地&#xff0c;或者强制提交到…

Chatbot 在教育中的应用

Chatbot 在教育中的应用 基本信息 ​ 这篇博客主要介绍几篇Chatbot在教育领域中应用的文章&#xff0c;根据文章的侧重点不同&#xff0c;分为介绍教育理论&#xff0c;与介绍系统设计两类。从问题定义、技术方法、教育学理论、实验设计、结论证据几个方面概括各篇文章。 博…

【字符串】Leetcode 43. 字符串相乘

题目讲解 43. 字符串相乘 算法讲解 class Solution { public:void AddZero(string& temp, int cnt) {while (cnt--) {temp 0;} }string Add(string num1, string num2) {string result;int carry 0;int i num1.size() - 1;int j num2.size() - 1;while (i > 0 ||…

电子信息工程专业就业前景怎么样

电子信息工程专业的就业前景十分广阔&#xff0c;主要得益于现代社会对信息技术的依赖不断加深以及科技的快速发展&#xff0c;以下是上大学网&#xff08;www.sdaxue.com&#xff09;对该专业就业前景的具体分析&#xff0c;供大家参考&#xff01; 行业需求广泛&#xff1a;随…

Sentinel流量防卫兵

1、分布式服务遇到的问题 服务可用性问题 服务可用性场景 服务雪崩效应 因服务提供者的不可用导致服务调用者的不可用,并将不可用逐渐放大的过程&#xff0c;就叫服务雪崩效应导致服务不可用的原因&#xff1a; 在服务提供者不可用的时候&#xff0c;会出现大量重试的情况&…

谁能取代迈巴赫,征服互联网安全大佬周鸿祎?

‍作者 |老缅 编辑 |德新 4月18日&#xff0c;「周鸿祎卖车」登上了微博热搜。这位360创始人、董事长发微博称&#xff1a;自己做了一个艰难的决定&#xff0c;将把陪伴9年的迈巴赫600给卖掉。 随后&#xff0c;他解释道&#xff1a;「这是因为我需要体验新一代车的感觉。古人…

锂电池SOH估计 | Matlab实现基于ALO-SVR模型的锂电池SOH估计

目录 预测效果基本介绍程序设计参考资料 预测效果 基本介绍 锂电池SOH估计 | Matlab实现基于ALO-SVR模型的锂电池SOH估计 蚁狮优化支持向量机锂电池健康状态SOH估计&#xff1b; 具体流程如下&#xff1b; 1、分析锂离子电池老化数据集&#xff0c;从中选取具有代表电池性能衰减…

Java进阶【十三期】:【异常处理】 (抛出捕获异常、自定义异常处理)、处理异常的几种方式 【(File】文件路径操作、File文件处理的综合练习

文章目录 Java进阶【十三期】&#xff1a;异常处理一、异常基本介绍二、编译异常和运行异常三、总结 异常的作用异常的处理方式一、JVM默认的处理方式二、自己处理异常自己 处理的问题 三、总结 Throwable 成员方法抛出异常总结 异常练习自定义异常 FileFile 三个 构造方法File…