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提高效率,提升自我。

相关推荐
丁先生qaq几秒前
热成像实例分割电力设备数据集(3类,838张)
人工智能·计算机视觉·目标跟踪·数据集
红衣小蛇妖21 分钟前
神经网络-Day45
人工智能·深度学习·神经网络
KKKlucifer38 分钟前
当AI遇上防火墙:新一代智能安全解决方案全景解析
人工智能
DisonTangor1 小时前
【小红书拥抱开源】小红书开源大规模混合专家模型——dots.llm1
人工智能·计算机视觉·开源·aigc
浠寒AI3 小时前
智能体模式篇(上)- 深入 ReAct:LangGraph构建能自主思考与行动的 AI
人工智能·python
weixin_505154463 小时前
数字孪生在建设智慧城市中可以起到哪些作用或帮助?
大数据·人工智能·智慧城市·数字孪生·数据可视化
Best_Me073 小时前
深度学习模块缝合
人工智能·深度学习
YuTaoShao4 小时前
【论文阅读】YOLOv8在单目下视多车目标检测中的应用
人工智能·yolo·目标检测
算家计算4 小时前
字节开源代码模型——Seed-Coder 本地部署教程,模型自驱动数据筛选,让每行代码都精准落位!
人工智能·开源
伪_装4 小时前
大语言模型(LLM)面试问题集
人工智能·语言模型·自然语言处理