跳到主要内容 十个实用的 Python 自动化脚本 | 极客日志
Python AI 算法
十个实用的 Python 自动化脚本 自动化任务通常耗时且重复。本文整理了十个基于 Python 的实用自动化脚本,涵盖图像处理、视频编辑、PDF 转换、API 请求、系统通知、文本纠错、文件下载及 GUI 开发等领域。通过 Pillow、Moviepy、PyMuPDF、Urllib3、Psutil、TextBlob 等库,实现批量裁剪图片、剪辑视频、电池电量提醒、语法拼写修正等功能。这些脚本可直接用于日常开发提效,帮助开发者减少重复劳动,专注于核心业务逻辑。
清心 发布于 2025/2/6 更新于 2026/4/21 2 浏览重复性任务往往耗时且枯燥,例如批量裁剪图片、纠正拼写错误或处理 API 请求。利用 Python 的丰富生态库,可以编写自动化脚本来替代这些工作,显著提升效率。
01. 图片优化器 该脚本基于 Pillow 模块,支持对图像进行裁剪、缩放、翻转、旋转、压缩及滤镜处理,功能类似于简易版 Photoshop。
from PIL import Image, ImageFilter, ImageOps, ImageEnhance
im = Image.open ("Image1.jpg" )
im = im.crop((34 , 23 , 100 , 100 ))
im = Image.open ("Image1.jpg" )
im = im.resize((50 , 50 ))
im = Image.open ("Image1.jpg" )
im = im.transpose(Image.FLIP_LEFT_RIGHT)
im = Image.open ("Image1.jpg" )
im = im.rotate(360 )
im = Image.open ("Image1.jpg" )
im.save("Image1.jpg" , optimize=True , quality=90 )
im = Image.open ("Image1.jpg" )
im = im.filter (ImageFilter.BLUR)
im = Image.open ("Image1.jpg" )
im = im.filter (ImageFilter.SHARPEN)
im = Image.open ("Image1.jpg" )
im = ImageEnhance.Brightness(im).enhance(1.5 )
im = Image.open ("Image1.jpg" )
im = ImageEnhance.Contrast(im).enhance(1.5 )
im = Image.open ("Image1.jpg" )
im = ImageOps.grayscale(im)
im = ImageOps.invert(im)
im = ImageOps.posterize(im, 4 )
im.save("Image1.jpg" )
02. 视频优化器 使用 Moviepy 模块可轻松实现视频剪辑、音频合成、速度调整及特效添加,适合快速构建视频编辑器。
import moviepy.editor as pyedit
video = pyedit.VideoFileClip("vid.mp4" )
vid1 = video.subclip(0 , 10 )
vid2 = video.subclip(20 , 40 )
final_vid = pyedit.concatenate_videoclips([vid1, vid2])
final_vid = final_vid.speedx(2 )
aud = pyedit.AudioFileClip("bg.mp3" )
final_vid = final_vid.set_audio(aud)
final_vid = final_vid.fx(pyedit.vfx.time_mirror)
vid1 = pyedit.VideoFileClip("vid1.mp4" )
vid2 = pyedit.VideoFileClip("vid2.mp4" )
final_vid = pyedit.concatenate_videoclips([vid1, vid2])
vid1 = final_vid.fx(pyedit.vfx.mirror_x)
vid2 = final_vid.fx(pyedit.vfx.invert_colors)
final_vid = pyedit.concatenate_videoclips([vid1, vid2])
img1 = pyedit.ImageClip("img1.jpg" )
img2 = pyedit.ImageClip("img2.jpg" )
final_vid = pyedit.concatenate_videoclips([img1, img2])
final_vid.write_videofile("final.mp4" )
03. PDF 转图片 PyMuPDF 模块能高效提取 PDF 页面并转换为 PNG 图像,适用于文档归档或预览场景。
import fitz
def pdf_to_images (pdf_file ):
doc = fitz.open (pdf_file)
for p in doc:
pix = p.get_pixmap()
output = f"page{p.number} .png"
pix.writePNG(output)
pdf_to_images("test.pdf" )
04. 获取 API 数据 Urllib3 提供了强大的 HTTP 客户端功能,支持 GET 和 POST 请求,便于从服务器获取或发送数据。
import urllib3
http = urllib3.PoolManager()
url = "https://api.github.com/users/psf/repos"
response = http.request('GET' , url)
print (response.status)
print (response.data)
url = "https://httpbin.org/post"
response = http.request('POST' , url, fields={'hello' : 'world' })
print (response.status)
05. 电池指示灯 结合 Psutil 和 Plyer 库,可监控系统电池状态并在电量低于阈值时发送桌面通知。
from plyer import notification
import psutil
from time import sleep
while True :
battery = psutil.sensors_battery()
life = battery.percent
if life < 50 :
notification.notify(
title="Battery Low" ,
message="Please connect to power source" ,
timeout=10
)
sleep(60 )
06. 语法修正器 利用 HappyTransformer 和 T5 模型,可自动扫描文本并修复语法错误,提升写作质量。
from happytransformer import HappyTextToText as HappyTTT
from happytransformer import TTSettings
def Grammar_Fixer (Text ):
Grammer = HappyTTT("T5" ,"prithivida/grammar_error_correcter_v1" )
config = TTSettings(do_sample=True , top_k=10 , max_length=100 )
corrected = Grammer.generate_text(Text, args=config)
print ("Corrected Text: " , corrected.text)
Text = "This is sample text we know this"
Grammar_Fixer(Text)
07. 拼写修正 TextBlob 库提供简单的接口来检测并修正单词拼写错误,适用于段落或单字纠错。
from textblob import *
def fix_paragraph_words (paragraph ):
sentence = TextBlob(paragraph)
correction = sentence.correct()
print (correction)
def fix_word_spell (word ):
word = Word(word)
correction = word.correct()
print (correction)
fix_paragraph_words("This is sample text!!" )
fix_word_spell("maangoo" )
08. 互联网下载器 通过 IDM 模块可创建多线程下载器,支持断点续传,用于批量下载文件或媒体资源。
import internetdownloadmanager as idm
def Downloader (url, output ):
pydownloader = idm.Downloader(worker=20 ,
part_size=1024 *1024 *10 ,
resumable=True )
pydownloader.download(url, output)
Downloader("Link url" , "image.jpg" )
Downloader("Link url" , "video.mp4" )
09. 获取世界新闻 调用 News API 接口,可根据关键词检索全球新闻,支持多语言和多地区筛选。
import requests
ApiKey = "YOUR_API_KEY"
url = f"https://api.worldnewsapi.com/search-news?text=hurricane&api-key={ApiKey} "
headers = {
'Accept' : 'application/json'
}
response = requests.get(url, headers=headers)
print ("News: " , response.json())
10. GUI 应用程序 PySide6 是跨平台 GUI 框架,可用于构建包含按钮、输入框、进度条等控件的现代桌面应用。
from PySide6.QtWidgets import *
from PySide6.QtGui import *
import sys
app = QApplication(sys.argv)
window = QWidget()
window.resize(500 , 500 )
window.setWindowTitle("PySide6 Window" )
button = QPushButton("Click Me" , window)
button.move(200 , 200 )
label = QLabel("Hello World" , window)
label.move(200 , 150 )
input_box = QLineEdit(window)
input_box.move(200 , 250 )
radio_button = QRadioButton("Radio Button" , window)
radio_button.move(200 , 300 )
checkbox = QCheckBox("Checkbox" , window)
checkbox.move(200 , 350 )
slider = QSlider(window)
slider.move(200 , 400 )
progress_bar = QProgressBar(window)
progress_bar.move(200 , 450 )
msg = QMessageBox(window)
msg.setText("Message Box" )
msg.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)
window.show()
sys.exit(app.exec ())
以上脚本覆盖了办公自动化、数据处理及界面开发等常见场景,开发者可根据实际需求组合使用,实现工作流的自动化。
相关免费在线工具 加密/解密文本 使用加密算法(如AES、TripleDES、Rabbit或RC4)加密和解密文本明文。 在线工具,加密/解密文本在线工具,online
RSA密钥对生成器 生成新的随机RSA私钥和公钥pem证书。 在线工具,RSA密钥对生成器在线工具,online
Mermaid 预览与可视化编辑 基于 Mermaid.js 实时预览流程图、时序图等图表,支持源码编辑与即时渲染。 在线工具,Mermaid 预览与可视化编辑在线工具,online
curl 转代码 解析常见 curl 参数并生成 fetch、axios、PHP curl 或 Python requests 示例代码。 在线工具,curl 转代码在线工具,online
Base64 字符串编码/解码 将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online
Base64 文件转换器 将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online