ChatGPT编程—实现小工具软件(批量替换文本、批量处理图像文件)

ChatGPT编程---实现小工具软件(批量替换文本、批量处理图像文件)

今天借助[小蜜蜂AI][https://zglg.work]网站的ChatGPT编程实现一个功能:批量处理文件及其内容,例如批量替换文本、批量处理图像文件等。

环境:Pycharm 2021

系统:Mac OS

向ChatGPT输入如下内容:

ChatGPT收到后返回如下结果:

批量处理文件及其内容:

1. 批量替换文本文件内容
  • 使用Python的fileinput模块结合正则表达式,可以轻松批量替换文本文件中的内容。
python 复制代码
import fileinput
import re

# 批量替换文本文件中的指定内容
def batch_replace_text(file_pattern, search_pattern, replace_text):
    for line in fileinput.input(files=glob.glob(file_pattern), inplace=True):
        print(re.sub(search_pattern, replace_text, line), end='')

# 调用示例:将所有.txt文件中的"old_text"替换为"new_text"
batch_replace_text("*.txt", "old_text", "new_text")

根据ChatGPT返回的结果,进行如下修改并运行,如下所示:

python 复制代码
import fileinput
import re
import glob


# 批量替换文本文件中的指定内容
def batch_replace_text(file_pattern, search_pattern, replace_text):
    for line in fileinput.input(files=glob.glob(file_pattern), inplace=True):
        print(re.sub(search_pattern, replace_text, line), end='')


# 调用示例:将所有.txt文件中的"old_text"替换为"new_text"
batch_replace_text("*.txt", "AI", "人工只能(AI,Artificial Intelligence)")
2. 批量处理图像文件
  • 使用Pillow库(PIL Fork)来批量处理图像文件,例如调整大小、转换格式等操作。
python 复制代码
from PIL import Image
import os

# 批量调整图像大小
def resize_images(input_dir, output_dir, size=(128, 128)):
    os.makedirs(output_dir, exist_ok=True)
    for filename in os.listdir(input_dir):
        if filename.endswith(('.png', '.jpg', '.jpeg')):
            img = Image.open(os.path.join(input_dir, filename))
            img_resized = img.resize(size)
            img_resized.save(os.path.join(output_dir, filename))

# 调用示例:将input_images目录中的所有图片调整为128x128尺寸并保存到output_images目录
resize_images("input_images", "output_images")

根据ChatGPT返回的结果,进行如下修改并运行,如下所示:

python 复制代码
from PIL import Image
import os


# 批量调整图像大小
height = input('请输入图片高度:')
width = input('请输入图片宽度:')


def resize_images(input_dir, output_dir, size=(int(height), int(width))):
    os.makedirs(output_dir, exist_ok=True)
    for filename in os.listdir(input_dir):
        if filename.endswith(('.png', '.jpg', '.jpeg')):
            img = Image.open(os.path.join(input_dir, filename))
            img_resized = img.resize(size)
            img_resized.save(os.path.join(output_dir, filename))


# 调用示例:将input_images目录中的所有图片调整为height*width尺寸并保存到output_images目录
resize_images("input_images", "output_images")

使用上述代码示例,您可以轻松地批量处理文本文件内容或图像文件。根据具体需求可进一步定制功能,并确保在处理大量文件时进行适当优化以提高效率。

还是那句话,AI编程太高效了。用好AI提高效率,提升自我。

相关推荐
Serverless社区11 分钟前
AgentRun实践指南:Agent 的宝藏工具—All-In-One Sandbox
人工智能
AngelPP16 分钟前
拆解 OpenClaw 上下文引擎:一个 AI Agent 是如何管理"记忆"的
人工智能
老纪的技术唠嗑局18 分钟前
OpenClaw + 6 个 Agent 运转半个月,从聊天到干活的完整工程实践
人工智能
Guo白给19 分钟前
openclaw飞书部署手册
人工智能
itpretty20 分钟前
如何用 skill-creator 创建、测试和优化 skill
人工智能·claude
蓝戒札记23 分钟前
效率神器 NotebookLM:构建高质量知识库的完整教程与落地最佳实践
人工智能
chaors24 分钟前
Langchain入门到精通0x02:ICEL
人工智能·langchain·ai编程
吴佳浩39 分钟前
什么是算力?
人工智能·pytorch·llm
charlex1 小时前
【陈同学】走进 AI Agent:从“对话框”到“自主智能体”
人工智能·agent
百度Geek说2 小时前
打造高效易用的Agent Skill
人工智能