分享 20 个超实用的 Python 脚本。
今天为大家整理了 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 = '[email protected]'
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, '[email protected]')
提示
: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 创建简单的聊天机器人