Featured image of post 实用工具脚本

实用工具脚本

记录一些用 python 实现简单的工具类脚本

public
Some utilities written in the Python language.
Python

办公类

微信机器人

🔗参考链接

仅支持Windows系统,Python版本要求是3.8+,运行时要打开微信,本质上是个屏幕识图+点击的操作,所以不会有封号危险

首先通过pip引入相关的包

pip install -i https://pypi.tuna.tsinghua.edu.cn/simple PyOfficeRobot -U
pip install -i https://mirrors.aliyun.com/pypi/simple python-office -U

然后在项目文件中调用

import PyOfficeRobot #微信机器人包
import office #办公软件包

使用方法

# 发送指定消息
PyOfficeRobot.chat.send_message(who='文件传输助手', message='python脚本测试')

# 发送文件
PyOfficeRobot.file.send_file(who='文件传输助手', file=r'D:\test\picture.JPG')

# 获取群聊列表
PyOfficeRobot.file.get_group_list()

# 群发消息
PyOfficeRobot.group.send()

文件处理类

批量 Word 转 PDF

同目录下新建input文件夹

import office # 导入python-office
import os
import win32com.client as win32 # 导入win32com

# path填写你存放word文件的位置
path = 'input/'

# 关闭word文档
office.word.docx2pdf(path=path)

JPG/PNG 转 Webp

同目录下新建inputoutput文件夹

# 作者:小骆同学
# 功能:图片批量转webp
# 日期:2023年07月25日
from PIL import Image, ImageCms
import os
import glob

# 记录已转换的文件数量
converted_count = 0

# 定义输入和输出文件夹路径
input_folder = 'input'
output_folder = 'output'

# 获取文件夹中所有JPEG
image_list = glob.glob(os.path.join(input_folder, '*.jpg'))

# 获取文件夹中所有PNG
# image_list = glob.glob(os.path.join(input_folder, '*.jpg')+os.path.join(input_folder, '*.png'))

# 获取文件夹中所有PNG和JPEG
# image_list = glob.glob(os.path.join(input_folder, '*.jpg'))+glob.glob(os.path.join(input_folder, '*.png'))

# 构造sRGB颜色转换器
srgb_profile = ImageCms.createProfile('sRGB')
srgb_transform = ImageCms.buildTransformFromOpenProfiles(srgb_profile, srgb_profile, 'RGB', 'RGB')

# 遍历所有图像文件并进行转换
for image_path in image_list:
    # 打开图像并转换为sRGB格式
    with Image.open(image_path) as im:
        srgb_im = ImageCms.applyTransform(im, srgb_transform)

        # 构造输出文件路径
        output_path = os.path.join(output_folder, os.path.basename(image_path).split('.')[0] + '.webp')

        # 保存转换后的图像文件
        srgb_im.save(output_path)

        # 更新已转换的文件数量并打印进度信息
        converted_count += 1
        print(f'Converted {converted_count} of {len(image_list)} files')
print('success!')

统计 PDF 页数

这个主要是一些学生党拿来打印店凑满剪用的

# 作者:小骆同学
# 功能:计算打印店满减
# 日期:2023年07月18日
import os
# python3.10 以上版本导入PyPDF4模块,3.10以下导入PyPDF2模块
from PyPDF4 import PdfFileReader

# 指定pdf所在目录
pdf_dir = 'count/'

# 初始化总页数
total_pages = 0

# 遍历pdf_dir下的所有pdf文件
for filename in os.listdir(pdf_dir):
    if filename.endswith('.pdf'):
        # 打开pdf文件
        with open(pdf_dir + filename, 'rb') as pdf_file:
            # 创建PdfFileReader对象
            pdf_reader = PdfFileReader(pdf_file)
            # 获取pdf文件页数
            num_pages = pdf_reader.getNumPages()
            # 更新总页数
            total_pages += num_pages
            # 输出文件名和页数
            print(f'{filename}: {num_pages} pages')
# 输出总页数
print(f'Total pages: {total_pages}')

# 暂停(防止cmd中运行时一闪而过)
os.system('pause')

专门开发的打印店计划通程序

# 作者:小骆同学
# 功能:计算打印店满减
# 日期:2023年07月18日
import os
# python3.10 以上版本导入PyPDF4模块,3.10以下导入PyPDF2模块
from PyPDF4 import PdfFileReader

# 指定pdf所在目录
pdf_dir = 'count/'

# 初始化总价格
total_price = 0

print('说明:如果满减为15-10,那么满减门槛为15,满减价格为10')

# 输入单价
price = input('请输入打印一页的单价(按下回车默认为0.05):') or 0.05
price = float(price)

# 输入满减门槛
threshold = input('请输入满减门槛(按下回车默认为15):') or 15
threshold = int(threshold)

# 输入满减价格
discount = input('请输入满减价格(按下回车默认为10):') or 10
discount = int(discount)

# 输入最低消费
min_price = input('请输入最低消费(按下回车默认为10):') or 10
min_price = int(min_price)

# 是否自定义页数
is_custom = input('是否自定义页数?(自定义页数直接输入数字,否则按下回车):') or '0'
if is_custom == '0':
    # 初始化总页数
    total_pages = 0
    # 遍历pdf_dir下的所有pdf文件
    for filename in os.listdir(pdf_dir):
        if filename.endswith('.pdf'):
            # 打开pdf文件
            with open(pdf_dir + filename, 'rb') as pdf_file:
                # 创建PdfFileReader对象
                pdf_reader = PdfFileReader(pdf_file)
                # 获取pdf文件页数
                num_pages = pdf_reader.getNumPages()
                # 更新总页数
                total_pages += num_pages
else:
    # 转换为int类型
    total_pages = int(is_custom)

# 计算总价格
if total_pages >= threshold:
    total_price = total_pages * price - discount
else:
    total_price = total_pages * price

if total_price < min_price:
    total_price = min_price

# 输出总页数
print(f'总页数为:{total_pages}')

# 输出总价格,保留两位小数
print(f'总价格为:{total_price:.2f}')

# 暂停(防止cmd中运行时一闪而过)
input('按回车键退出')

HTML 文件压缩

如果只压缩HTML而不而压缩其中的JS和CSS

# 作者:小骆同学
# 功能:HTML文件压缩
# 日期:2023年08月01日
import os
import htmlmin

def compress_html_files(input_dir, options):
    # 遍历目录及其子目录中的所有文件和文件夹
    for root, dirs, files in os.walk(input_dir):
        for file in files:
            if file.endswith('.html'):
                # 读取HTML文件内容
                file_path = os.path.join(root, file)
                with open(file_path, 'r', encoding='utf-8') as f:
                    content = f.read()
                # 压缩HTML文件内容
                compressed_content = htmlmin.minify(content, **options)

                # 将压缩后的内容写回到源文件中
                with open(file_path, 'w', encoding='utf-8') as f:
                    f.write(compressed_content)
                    print(f'Compressed {file_path}')
# 调用函数
input_dir = './input'
options = {
    'remove_comments': True,
    'remove_empty_space': True,
    'remove_all_empty_space': True,
    'reduce_boolean_attributes': True,
    'remove_optional_attribute_quotes': True,
}
compress_html_files(input_dir, options)

压缩HTML文件中的JS和CSS

需要特别注意,如果你的文章代码块中有JS或CSS代码,那么他们也会一起被压缩成一行,谨慎使用!

# 作者:小骆同学
# 功能:HTML文件压缩
# 日期:2023年08月01日
import os

import htmlmin
from csscompressor import compress as compress_css
from jsmin import jsmin


def compress_html_file(file_path):
    with open(file_path, 'r', encoding='utf-8') as f:
        html = f.read()
    compressed_html = htmlmin.minify(html, remove_comments=True, remove_all_empty_space=True,
                                     reduce_empty_attributes=True, remove_optional_attribute_quotes=False)
    compressed_html = compressed_html.replace('\n', '')  # 移除换行符
    compressed_html = compressed_html.replace('\t', '')  # 移除制表符
    compressed_html = compressed_html.replace('\r', '')  # 移除回车符
    compressed_css = compress_css(compressed_html)  # 压缩 CSS 代码
    print(f'Compressed CSS in {file_path}')
    compressed_js = jsmin(compressed_html, quote_chars="'\"`")  # 压缩 JavaScript 代码
    print(f'Compressed JavaScript in {file_path}')
    # 将压缩后的 CSS 和 JavaScript 代码插入到 HTML 文件中
    compressed_html = compressed_html.replace('<style>' + compressed_css + '</style>',
                                              '<style>' + compressed_css + '</style><script>' + compressed_js + '</script>')
    compressed_html = compressed_html.strip()  # 移除首尾空格
    with open(file_path, 'w', encoding='utf-8') as f:
        f.write(compressed_html)

def compress_html_files_in_folder(folder_path):
    for root, dirs, files in os.walk(folder_path):
        for file in files:
            if file.endswith('.html'):
                file_path = os.path.join(root, file)
                compress_html_file(file_path)

if __name__ == '__main__':
    folder_path = 'input'
    compress_html_files_in_folder(folder_path)
    print('HTML files compressed successfully')

图像分辨率调整

参考 🔗 相册优化小记

# 作者:小骆同学
# 日期:2023年08月30日

import os

from PIL import Image


def resize_to_25_percent(input_path, output_path):
    # 打开图像
    img = Image.open(input_path)

    # 获取原始分辨率
    original_width, original_height = img.size

    # 计算新的宽度和高度(25%分辨率)
    new_width = int(original_width * 0.20)
    new_height = int(original_height * 0.20)

    # 调整分辨率
    resized_img = img.resize((new_width, new_height), Image.LANCZOS)

    # 保存调整后的图像
    resized_img.save(output_path)


# 输入文件夹和输出文件夹路径
input_folder = 'input'  # 替换为你的输入文件夹路径
output_folder = 'output-resize'  # 替换为你的输出文件夹路径

# 确保输出文件夹存在
if not os.path.exists(output_folder):
    os.makedirs(output_folder)

# 遍历输入文件夹中的所有图片文件
for filename in os.listdir(input_folder):
    if filename.lower().endswith(('.jpg', '.jpeg', '.png', '.gif')):
        input_path = os.path.join(input_folder, filename)
        output_path = os.path.join(output_folder, filename)

        # 调整图像分辨率为原始的25%
        resize_to_25_percent(input_path, output_path)
        print(f"resize:{input_path} => {output_path}")

print("success!")
Licensed under CC BY-NC-SA 4.0
最后更新于 2023 年 9 月 19 日