微博登录网站开发,饲料行业建设网站方案设计免费下载ppt,社交网站解决方案,张店学校网站建设公司ChatGPT编程—实现小工具软件(批量替换文本、批量处理图像文件)
今天借助[小蜜蜂AI][https://zglg.work]网站的ChatGPT编程实现一个功能#xff1a;批量处理文件及其内容#xff0c;例如批量替换文本、批量处理图像文件等。
环境#xff1a;Pycharm 2021
系统#xff1a…ChatGPT编程—实现小工具软件(批量替换文本、批量处理图像文件)
今天借助[小蜜蜂AI][https://zglg.work]网站的ChatGPT编程实现一个功能批量处理文件及其内容例如批量替换文本、批量处理图像文件等。
环境Pycharm 2021
系统Mac OS
向ChatGPT输入如下内容
ChatGPT收到后返回如下结果
批量处理文件及其内容
1. 批量替换文本文件内容
使用Python的fileinput模块结合正则表达式可以轻松批量替换文本文件中的内容。
import fileinput
import re# 批量替换文本文件中的指定内容
def batch_replace_text(file_pattern, search_pattern, replace_text):for line in fileinput.input(filesglob.glob(file_pattern), inplaceTrue):print(re.sub(search_pattern, replace_text, line), end)# 调用示例将所有.txt文件中的old_text替换为new_text
batch_replace_text(*.txt, old_text, new_text)根据ChatGPT返回的结果进行如下修改并运行如下所示
import fileinput
import re
import glob# 批量替换文本文件中的指定内容
def batch_replace_text(file_pattern, search_pattern, replace_text):for line in fileinput.input(filesglob.glob(file_pattern), inplaceTrue):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来批量处理图像文件例如调整大小、转换格式等操作。
from PIL import Image
import os# 批量调整图像大小
def resize_images(input_dir, output_dir, size(128, 128)):os.makedirs(output_dir, exist_okTrue)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返回的结果进行如下修改并运行如下所示
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_okTrue)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提高效率提升自我。