本文主要是介绍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:
一共就两步:
- 安装PyInstaller
pip install pyinstaller
- 使用PyInstaller打包
pyinstaller --onefile --windowed file_renamer_gui.py
注意要把“file_renamer_gui.py"替换成你自己的文件名。
打包好之后,在项目目录的dist文件夹下就可以找到打包好的文件。
双击打开即可运行,效果是一样的。
好了,这个工具就写好了。
有了AI的助攻,我们想写什么工具直接让AI帮我们写就好了,是不是给了你很大的信心?
原来编程也不难,编程我也会啊~
上面的代码亲测可用,如果你想直接下载exe文件,关注公众号“编程我也会”,回复“重命名”即可下载。
这篇关于AI神助攻!小白也能制作自动重命名工具~的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!