【Python】20个超级脚本,让你日常工作有如神助

分享 20 个超实用的 Python 脚本。

bbfa04bf18ce8122c6932cffc47b3082.jpeg

今天为大家整理了 20 个超实用的 Python 脚本。

这些脚本能自动搞定繁琐任务,解决潜在问题。且每个脚本都有详细代码示例,助你轻松上手。下面详细介绍这些实用的 Python 脚本,一起看看吧。

1 文件重复查找器(延长硬盘使用寿命)

该脚本的功能是识别并清理指定目录下的重复文件,以释放存储空间。

import os
import hashlib


def find_duplicates(folder):
    hashes = {}
    for dirpath, _, filenames in os.walk(folder):
        for file in filenames:
            filepath = os.path.join(dirpath, file)
            with open(filepath, 'rb') as f:
                file_hash = hashlib.md5(f.read()).hexdigest()
                if file_hash in hashes:
                    print(f"Duplicate found: {filepath} and {hashes[file_hash]}")
                else:
                    hashes[file_hash] = filepath


find_duplicates('path/to/your/folder')

提示:定期运行此脚本,有助于保持硬盘的整洁,优化存储性能。

2 自动整理下载文件夹

你是不是觉得下载文件夹常常杂乱无章呢?此脚本会依据文件的扩展名,将文件分类整理到不同的子文件夹中:

import os
import shutil


def organize_folder(folder):
    extensions = {
        'Images': ['.jpg', '.png', '.gif'],
        'Documents': ['.pdf', '.docx', '.txt'],
        'Videos': ['.mp4', '.mkv'],
        'Archives': ['.zip', '.rar'],
    }
    for file in os.listdir(folder):
        filepath = os.path.join(folder, file)
        if os.path.isfile(filepath):
            ext = os.path.splitext(file)[1].lower()
            for category, exts in extensions.items():
                if ext in exts:
                    category_path = os.path.join(folder, category)
                    os.makedirs(category_path, exist_ok=True)
                    shutil.move(filepath, os.path.join(category_path, file))


organize_folder('path/to/downloads')

提示:杂乱的下载文件夹会延长文件查找时间,使用此脚本可避免这一问题。

3 批量图片缩放器

能把指定文件夹中的图片批量缩放到统一尺寸,使其适合在各种社交平台使用。

from PIL import Image
import os


def batch_resize(folder, size=(800, 800)):
    for file in os.listdir(folder):
        if file.endswith(('jpg', 'png')):
            filepath = os.path.join(folder, file)
            img = Image.open(filepath)
            img = img.resize(size)
            img.save(filepath)


batch_resize('path/to/images')

提示:针对不同平台优化图片,可有效提升用户体验。

4 实时天气通知器

此脚本使用 OpenWeatherMap API 来获取当前的天气状况。

import requests


def get_weather(city):
    api_key = 'your_api_key_here'
    url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}"
    response = requests.get(url).json()
    if response['cod'] == 200:
        print(f"Weather in {city}: {response['weather'][0]['description']}, Temp: {response['main']['temp']}K")
    else:
        print(f"City not found!")


get_weather('London')

提示:Python可以与API交互,从气象服务获取实时数据。

5 Reddit 最新帖子邮件发送器

能将指定子版块的最新帖子发送到个人邮箱,是 Reddit 爱好者的福音!

import requests
import smtplib


def send_email(subject, body, to_email):
    from_email = 'your_email@gmail.com'
    password = 'your_password'
    with smtplib.SMTP('smtp.gmail.com', 587) as smtp:
        smtp.starttls()
        smtp.login(from_email, password)
        msg = f"Subject: {subject}\n\n{body}"
        smtp.sendmail(from_email, to_email, msg)


def get_reddit_posts(subreddit):
    url = f"https://www.reddit.com/r/{subreddit}/new.json"
    headers = {'User-Agent': 'Python Script'}
    response = requests.get(url, headers=headers).json()
    posts = [post['data']['title'] for post in response['data']['children'][:5]]
    return '\n'.join(posts)


posts = get_reddit_posts('python')
send_email('Latest Reddit Posts', posts, 'recipient_email@example.com')

提示:Reddit 每月活跃用户超 4.3 亿,是座信息宝库。

6 网页转电子书工具

可将任意网页保存为 PDF 格式,方便你进行离线阅读。

import pdfkit


def webpage_to_pdf(url, output_file):
    pdfkit.from_url(url, output_file)


webpage_to_pdf('https://example.com', 'output.pdf')

提示:Python 的 Beautiful Soup 和 HTML2Text 库可用于网页抓取和格式处理。

7 文本转语音功能

使用文本转语音库,让 Python 朗读文本,开启旁白模式。

import pyttsx3


def text_to_speech(text):
    engine = pyttsx3.init()
    engine.say(text)
    engine.runAndWait()


text_to_speech("Hello, this is Python speaking!")

提示:可尝试使用不同的声音和口音,让朗读效果更具吸引力。

8 网站可用性检查器

该脚本专为网站管理员设计,通过发送请求检查网站是否正常运行。

import requests


def check_website(url):
    try:
        response = requests.get(url)
        if response.status_code == 200:
            print(f"{url} is up and running!")
        else:
            print(f"{url} returned status code {response.status_code}")
    except Exception as e:
        print(f"Error: {e}")


check_website('https://example.com')

提示:议定期运行此脚本,以便有效监控网站的正常运行时间。

9 加密货币价格追踪器

能够轻松实现对加密货币实时价格的监控。

import requests


def track_crypto(crypto):
    url = f"https://api.coingecko.com/api/v3/simple/price?ids={crypto}&vs_currencies=usd"
    response = requests.get(url).json()
    price = response.get(crypto, {}).get('usd', 'N/A')
    print(f"The current price of {crypto} is ${price}")


track_crypto('bitcoin')

提示:无需不断刷新网页,就能随时了解你的投资动态。

10 下载完成自动关机功能

用Python安排自动关机。

import os
import time


def shutdown_after(seconds):
    print(f"Your PC will shut down in {seconds} seconds...")
    time.sleep(seconds)
    os.system("shutdown /s /t 1")


shutdown_after(3600)  # 1 hour

提示:很多人在下载文件时会让电脑整晚处于运行状态,此脚本可避免这种情况。

11 脚本密码保护功能

为Python脚本添加密码提示,保护敏感信息。

import getpass


def password_protect(password):
    user_input = getpass.getpass("Enter the password to access the script: ")
    if user_input == password:
        print("Access granted!")
    else:
        print("Access denied!")


password_protect("your_secure_password")

提示:保护敏感信息对维护隐私和安全至关重要。

12 监控CPU 使用率

用于密切监控计算机的 CPU 使用率,防止电脑过热,确保性能稳定。

import psutil
import time


def monitor_cpu():
    while True:
        cpu_usage = psutil.cpu_percent(interval=1)
        print(f"Current CPU usage: {cpu_usage}%")
        time.sleep(5)  # Check every 5 seconds


monitor_cpu()

提示:可设置 CPU 使用率的阈值,当超过该阈值时发出警报。

13 PDF 转文本功能

从PDF文件中提取文本,便于阅读和编辑。

from PyPDF2 import PdfReader


def pdf_to_text(pdf_file):
    reader = PdfReader(pdf_file)
    text = ""
    for page in reader.pages:
        text += page.extract_text()
    return text


text = pdf_to_text('your_file.pdf')
print(text)

提示:从PDF中提取文本,便于编辑和数据提取。

14 二维码生成功能

可以轻松为网址、文本或其他数据生成二维码。

import qrcode


def generate_qr(data):
    img = qrcode.make(data)
    img.save('qr_code.png')


generate_qr('https://example.com')

提示:可自定义二维码的设计,使其更具视觉美感。

15  YouTube 视频下载

使用简单的脚本,可轻松下载 YouTube 上的视频,让你免受烦人的广告打扰。

from pytube import YouTube


def download_youtube_video(url):
    yt = YouTube(url)
    stream = yt.streams.get_highest_resolution()
    stream.download()


download_youtube_video('https://www.youtube.com/watch?v=example')

16 随机强密码生成功能

为你的账户生成强密码,避免使用诸如 “Password123” 之类的弱密码。

import random
import string


def generate_password(length=12):
    characters = string.ascii_letters + string.digits + string.punctuation
    password = ''.join(random.choice(characters) for i in range(length))
    return password


print(generate_password(16))

提示:强密码对于保护在线账户免受未经授权的访问至关重要。

17 获取实时股票价格

帮助投资者获取心仪股票的当前股价。

import requests


def get_stock_price(symbol):
    url = f"https://api.example.com/stocks/{symbol}/price"  # Replace with a valid stock API
    response = requests.get(url).json()
    price = response.get('price', 'N/A')
    print(f"The current price of {symbol} is ${price}")


get_stock_price('AAPL')  # Example: Apple Inc.

提示:Python的requests库简化了与API的交互,便于获取股票数据。

18 创建简单的聊天机器人

构建一个能响应用户输入的基础聊天机器人。

def chatbot():
    print("Hello! I'm your friendly chatbot. Type 'exit' to stop.")
    while True:
        user_input = input("You: ")
        if user_input.lower() == 'exit':
            print("Chatbot: Goodbye!")
            break
        print(f"Chatbot: You said '{user_input}'.")


chatbot()

提示:在探索复杂的 AI 模型之前,先从基于规则的基础聊天机器人开始。

19 步数计数器

创建简单的步数计数器,用于记录每日的步数。

steps = 0


def add_steps(num_steps):
    global steps
    steps += num_steps
    print(f"Total steps today: {steps}")


# Example usage
add_steps(1000)  # Log 1000 steps

提示:记录步数能帮助你了解自己的运动情况,鼓励保持健康的生活方式。

20. **创建办事项列表

用简单的命令行待办事项列表应用程序,轻松管理任务。

tasks = []


def add_task(task):
    tasks.append(task)
    print(f"Task added: {task}")


def show_tasks():
    print("Your To-Do List:")
    for idx, task in enumerate(tasks):
        print(f"{idx + 1}. {task}")


add_task("Finish Python scripts")
show_tasks()

提示:待办事项列表能帮你规划工作,提高效率,确保各项任务有序完成。

结语

有了这20个Python脚本,你可以成为更高效的开发者,自动完成各种日常操作。无论是文件管理、数据提取,还是创建二维码,Python都提供了优化工作流程所需的实用工具。

现在就将这些脚本应用起来,你会体验到如何将重复性的琐事转化为节省时间、提升自我的自动化流程,让你的工作和生活更加轻松高效。

推荐书单

《Python项目开发全程实录》

本书精选12个热门项目,涉及Python基础应用、游戏开发、网络爬虫、大数据及可视化分析、Web开发、人工智能开发六大Python重点应用方向,实用性非常强。具体项目包含:简易五子棋(控制台版)、学生信息管理系统(基础版)、水果消消乐游戏、超级玛丽冒险游戏、汽车之家图片抓取工具等。本书从软件工程的角度出发,按照项目开发的顺序,系统、全面地讲解每一个项目的开发实现过程。

本书可为Python入门自学者提供更广泛的项目实战场景,可为计算机专业学生进行项目实训、毕业设计提供项目参考,可供计算机专业教师、IT培训讲师用作教学参考资料,还可作为软件工程师、IT求职者、编程爱好者进行项目开发时的参考书。

【5折促销中】购买链接:https://item.jd.com/14804356.html

精彩回顾

10个Python自动化脚本,日常工作更轻松

10个Python编程脚本,超能力再升级

10个Python开发者必备的SQL小技巧

15个有趣的Python脚本,让你从入门到精通

20个Python编程脚本,让你拥有超能力

2cb5dacdd074eb2898c27e563b0830ba.jpeg

长按关注《Python学研大本营》,加入读者群

9e43727893e1fecc4ba166eea44bcacb.png

长按访问【IT今日热榜】,发现每日技术热点
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值