跳过正文

Python 自动化脚本合集

Python 自动化脚本
目录

重复性的任务往往费时又枯燥,比如裁剪 100 张照片、获取 API 数据、修复拼写错误等操作,为什么不使用 Python 来自动完成这些工作呢?在本文中,我将为你介绍 10 个实用的 Python 自动化脚本。

请将本文加入你的收藏夹,在不断进步的 IT 行业中,自动化脚本会是你提升效率的好帮手。


图像优化器
#

这个脚本使用 Pillow 模块,可以轻松完成图像裁剪、缩放、旋转、压缩、模糊、锐化、调整亮度和对比度等操作。

# pip install Pillow
import PIL
# 裁剪
im = PIL.Image.open("Image1.jpg")
im = im.crop((34, 23, 100, 100))
# 缩放
im = im.resize((50, 50))
# 水平翻转
im = im.transpose(PIL.Image.FLIP_LEFT_RIGHT)
# 旋转
im = im.rotate(360)
# 压缩
im.save("Image1.jpg", optimize=True, quality=90)
# 模糊
im = im.filter(PIL.ImageFilter.BLUR)
# 锐化
im = im.filter(PIL.ImageFilter.SHARPEN)
# 设置亮度
im = PIL.ImageEnhance.Brightness(im)
im = im.enhance(1.5)
# 设置对比度
im = PIL.ImageEnhance.Contrast(im)
im = im.enhance(1.5)
# 添加滤镜
im = PIL.ImageOps.grayscale(im)
im = PIL.ImageOps.invert(im)
im = PIL.ImageOps.posterize(im, 4)
# 保存
im.save("Image1.jpg")

视频优化器
#

使用 MoviePy 模块可对视频进行剪辑、添加音频、加速播放、添加特效等操作。

# pip install 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")

PDF 转图片
#

使用 PyMuPDF 模块将 PDF 页转换为 PNG 图像,适合批量文档图像化处理。

# pip install PyMuPDF
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")

获取 API 数据
#

使用 urllib3 模块进行 API 的 GET 和 POST 请求操作。

# pip install urllib3
import urllib3
url = "https://api.github.com/users/psf/repos"
http = urllib3.PoolManager()
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)

电池电量提醒
#

当电池电量低于指定百分比时发出提醒,适用于笔记本用户。

# pip install 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="电量不足",
            message="请连接电源",
            timeout=10
        )
    sleep(60)

语法纠错器
#

通过 HappyTransformer 模块纠正文本语法错误,适合校对文章或段落。

# pip install happytransformer
from happytransformer import HappyTextToText as HappyTTT, TTSettings
def grammar_fixer(text):
    model = HappyTTT("T5", "prithivida/grammar_error_correcter_v1")
    config = TTSettings(do_sample=True, top_k=10, max_length=100)
    result = model.generate_text(text, args=config)
    print("修正后文本:", result.text)
grammar_fixer("This is smple tet we how know this")

拼写修正器
#

使用 TextBlob 模块修复句子或单词中的拼写错误。

# pip install textblob
from textblob import TextBlob, Word
def fix_paragraph_words(text):
    corrected = TextBlob(text).correct()
    print(corrected)

def fix_word_spell(word):
    corrected = Word(word).correct()
    print(corrected)

fix_paragraph_words("This is sammple tet!!")
fix_word_spell("maangoo")

互联网下载器
#

用 IDM 模块创建 Python 下载工具,支持断点续传。

# pip install internetdownloadmanager
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("链接地址", "image.jpg")
Downloader("链接地址", "video.mp4")

世界新闻获取器
#

使用 World News API 获取最新国际新闻,支持按国家和语言筛选。

# pip install requests
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("新闻内容:", response.json())

PySide2 图形界面应用
#

使用 PySide2 创建跨平台 GUI 应用,适合快速开发桌面工具。

# pip install PySide2
from PySide6.QtWidgets import *
from PySide6.QtGui import *
import sys

app = QApplication(sys.argv)
window = QWidget()
window.resize(500, 500)
window.setWindowTitle("PySide2 窗口")

QPushButton("点击我", window).move(200, 200)
QLabel("Hello Medium", window).move(200, 150)
QLineEdit(window).move(200, 250)
QRadioButton("单选按钮", window).move(200, 300)
QCheckBox("复选框", window).move(200, 350)
QSlider(window).move(200, 400)
QProgressBar(window).move(200, 450)

msg = QMessageBox(window)
msg.setText("消息框")
msg.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)

window.show()
sys.exit(app.exec())

这些脚本将为你的 Python 自动化之路提供灵感和实用工具,别忘了点赞转发!

相关文章

Python基本语法100条
程序 Python
9个实用python实例
程序 Python
英特尔年度发明家跳槽至三星
Intel 年度发明家