20 個(gè) Python 非常實(shí)用的自動(dòng)化腳本
假設(shè)你已經(jīng)用 Python 編碼一段時(shí)間了,并且在編碼方面非常自信,但我還是建議你認(rèn)真閱讀下本次推文。
這里有 20 個(gè) Python 腳本,如果你都掌握了,相信你的同事將會(huì)對(duì)你印象深刻、將那些看似不可自動(dòng)化的事情自動(dòng)化完成,并解決你甚至不知道的問題。
1. 文件重復(fù)查找器
是否曾經(jīng)查看過硬盤并想知道,為什么我只剩下 100MB?有一種非常討厭的事情就是文件重復(fù)。以下是查找重復(fù)文件和刪除它們的腳本:
import os
import hashlib
def hash_file(filename):
h = hashlib.md5()
with open(filename, 'rb') as file:
while chunk := file.read(8192):
h.update(chunk)
return h.hexdigest()
def find_duplicates(folder):
hashes = {}
for dirpath, _, filenames in os.walk(folder):
for f in filenames:
full_path = os.path.join(dirpath, f)
file_hash = hash_file(full_path)
if file_hash in hashes:
print(f"Duplicate found: {full_path} == {hashes[file_hash]}")
else:
hashes[file_hash] = full_path
find_duplicates('/path/to/your/folder')
ps:主要不要在系統(tǒng)文件夾上盲目運(yùn)行此操作。
我曾經(jīng)在舊項(xiàng)目文件夾上運(yùn)行這個(gè)程序后,在不到 10 分鐘的時(shí)間內(nèi)釋放了 10GB 的空間。
2. 自動(dòng)整理下載文件夾
我們基本不會(huì)認(rèn)真整理下載文件夾內(nèi)的內(nèi)容,下面是一個(gè)可以整齊地組織所有內(nèi)容的腳本:
import os
import shutil
def organize_folder(folder):
file_types = {
'Images': ['.jpeg', '.jpg', '.png', '.gif'],
'Videos': ['.mp4', '.avi', '.mov'],
'Documents': ['.pdf', '.docx', '.txt'],
'Archives': ['.zip', '.rar']
}
for filename in os.listdir(folder):
file_path = os.path.join(folder, filename)
if os.path.isfile(file_path):
ext = os.path.splitext(filename)[1].lower()
for folder_name, extensions in file_types.items():
if ext in extensions:
target_folder = os.path.join(folder, folder_name)
os.makedirs(target_folder, exist_ok=True)
shutil.move(file_path, os.path.join(target_folder, filename))
print(f'Moved {filename} to {folder_name}')
organize_folder('/path/to/Downloads')
相信你也一樣,根本沒有時(shí)間手動(dòng)組織文件,那就用起來吧。
3. 批量圖像調(diào)整器
正在處理需要調(diào)整圖像大小的項(xiàng)目?下面介紹如何輕松批量調(diào)整圖像大?。?/p>
from PIL import Image
import os
def batch_resize(folder, width, height):
for filename in os.listdir(folder):
if filename.endswith(('.jpeg', '.jpg', '.png')):
優(yōu)勢(shì) = Image.open(os.path.join(folder, filename))
優(yōu)勢(shì) = 優(yōu)勢(shì).resize((width, height))
優(yōu)勢(shì).save(os.path.join(folder, f"resized_{filename}"))
print(f'Resized {filename}')
batch_resize('/path/to/images', 800, 600)
當(dāng)你的領(lǐng)導(dǎo)想要 “在 5 分鐘內(nèi)裁剪并調(diào)整這些圖像的大小” 時(shí),這非常適合。
4. 實(shí)時(shí)天氣通知
每小時(shí)獲取實(shí)時(shí)天氣更新,再也不會(huì)忘記帶傘:
import requests
import time
API_KEY = 'your_api_key'
CITY = 'New York'
def get_weather():
url = f"http://api.openweathermap.org/data/2.5/weather?q={CITY}&appid={API_KEY}"
response = requests.get(url)
data = response.json()
return data['weather'][0]['description'], data['main']['temp'] - 273.15
while True:
weather, temp = get_weather()
print(f"Current weather in {CITY}: {weather}, {temp:.2f}°C")
time.sleep(3600) # Run every hour
雖然天氣app使用起來也比較方便,但這也是一種裝x的方式,哈哈哈。
5. 發(fā)送電子郵件
如果你對(duì)某個(gè)特定的博客網(wǎng)站很著迷,但又不想經(jīng)常檢查它,這里有一個(gè) Python 腳本,它可以將最新的reddit 帖子直接發(fā)送到你的收件箱:
import smtplib
import requests
def send_email(subject, body):
from_addr = 'your_email@example.com'
to_addr = 'your_email@example.com'
msg = f"Subject: {subject}\n\n{body}"
with smtplib.SMTP('smtp.gmail.com', 587) as server:
server.starttls()
server.login('your_email@example.com', 'your_password')
server.sendmail(from_addr, to_addr, msg)
def get_reddit_posts(subreddit):
url = f"https://www.reddit.com/r/{subreddit}/new.json"
headers = {'User-agent': 'Mozilla/5.0'}
response = requests.get(url, headers=headers)
data = response.json()
return [post['data']['title'] for post in data['data']['children']]
posts = get_reddit_posts('python')
send_email('Latest Reddit Posts', '\n'.join(posts))
自動(dòng)化可以節(jié)省大量時(shí)間。
6. 將任何網(wǎng)頁轉(zhuǎn)換為電子書
此腳本將您最喜歡的文章轉(zhuǎn)換成電子書格式,非常適合離線閱讀:
import requests
from bs4 import BeautifulSoup
from ebooklib import epub
def create_ebook(url, book_title):
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')
book = epub.EpubBook()
book.set_title(book_title)
chapter = epub.EpubHtml(title='Chapter 1', file_name='chap_01.xhtml')
chapter.content = soup.prettify()
book.add_item(chapter)
book.spine = ['nav', chapter]
epub.write_epub(f'{book_title}.epub', book, {})
create_ebook('https://example.com/your-favorite-article', 'My eBook')
7. 將文本轉(zhuǎn)換為語音
聽書比看書來得輕松,此腳本可將文本轉(zhuǎn)換為語音:
import pyttsx3
def text_to_speech(text):
engine = pyttsx3.init()
engine.say(text)
engine.runAndWait()
text_to_speech('Hello World, Python is amazing!')
Ps:這個(gè)技術(shù)恐怕只能拿來炫技,使用它來發(fā)現(xiàn)錯(cuò)誤或者只是讓自己在閱讀時(shí)休息一下,不是非常實(shí)用。
8. 檢查網(wǎng)站可用性
想知道你的網(wǎng)站是否癱瘓?這里有一個(gè)簡(jiǎn)單的腳本可以幫你檢查:
import requests
def is_website_online(url):
try:
response = requests.get(url)
return response.status_code == 200
except:
return False
print(is_website_online('https://example.com'))
如果你自建了一個(gè)網(wǎng)站,有一天當(dāng)你醒來發(fā)現(xiàn)你的網(wǎng)站已癱瘓 4 個(gè)小時(shí)時(shí),這個(gè)時(shí)候就會(huì)發(fā)現(xiàn)這個(gè)代碼的好處了。
9. 跟蹤加密貨幣價(jià)格
使用此腳本跟蹤你最喜歡的加密貨幣價(jià)格:
import requests
def get_crypto_price(crypto):
url = f"https://api.coindesk.com/v1/bpi/currentprice/{crypto}.json"
response = requests.get(url)
data = response.json()
return data['bpi']['USD']['rate']
print(get_crypto_price('BTC'))
10.下載完成后關(guān)閉電腦
再也不用等著下載完畢在關(guān)電腦了。讓你的計(jì)算機(jī)自行處理。此腳本會(huì)在下載完成后關(guān)閉 PC:
import os
import time
def check_downloads():
while True:
if not os.listdir('/path/to/downloads'):
print("Shutting down...")
os.system("shutdown /s /t 1")
time.sleep(60)
check_downloads()
11. 使用密碼保護(hù)你的腳本
這里有一個(gè)有趣的例子:用密碼保護(hù)你的腳本,這樣就沒有人可以在未經(jīng)許可的情況下運(yùn)行它們:
import getpass
password = getpass.getpass('Enter your password: ')
if password != 'secret':
print('Access Denied')
exit()
else:
print('Access Granted')
# Your protected code here
Ps:將其與加密方法結(jié)合,可獲得雙重保護(hù)。
12. 監(jiān)控計(jì)算機(jī)的 CPU 使用情況
留意 CPU 溫度和使用情況:
import psutil
def monitor_cpu():
print(f"CPU usage: {psutil.cpu_percent()}%")
print(f"Memory usage: {psutil.virtual_memory().percent}%")
monitor_cpu()
因?yàn)镃PU過熱絕對(duì)不是什么好事。當(dāng)然,也有專門應(yīng)用可以直接使用,但作為編程大佬的你,直接上代碼不是很酷么!
13. 將 PDF 轉(zhuǎn)換為文本
如果你經(jīng)常處理 PDF,此腳本將為提取文本提供一些思路:
import PyPDF2
def pdf_to_text(pdf_file):
reader = PyPDF2.PdfReader(pdf_file)
text = ''
for page in reader.pages:
text += page.extract_text()
return text
print(pdf_to_text('example.pdf'))
現(xiàn)在你可以輕松提取關(guān)鍵信息,而無需無休止地復(fù)制粘貼。
14. 生成二維碼
為任何 URL 或文本創(chuàng)建二維碼:
import qrcode
def generate_qr(text, filename):
code = qrcode.make(text)
code.save(f"{filename}.png")
generate_qr('https://example.com', 'my_qr_code')
誰知道二維碼可以這么簡(jiǎn)單?
15. 下載 YouTube 視頻
在幾秒鐘內(nèi)下載您喜愛的 YouTube 視頻:
import yt_dlp
def download_video(url):
# yt-dlp 的選項(xiàng)
ydl_opts = {
'format' : 'best' , # 下載最佳可用質(zhì)量
'outtmpl' : '%(title)s.%(ext)s' , # 將文件名設(shè)置為視頻標(biāo)題
'noplaylist' : True , # 如果 URL 是播放列表的一部分,則下載單個(gè)視頻
'quiet' : False , # 在控制臺(tái)中顯示下載進(jìn)度
'ignoreerrors' : True , # 即使遇到錯(cuò)誤也繼續(xù)
'no_warnings' : True , # 抑制警告
}
try :
# 使用 yt-dlp 下載視頻
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
ydl.download([url])
print ( "下載已成功完成。" )
except Exception as e:
print ( f"發(fā)生錯(cuò)誤:{e}" )
# 用所需的 YouTube 視頻 URL 替換
download_video('https://www.youtube.com/watch?v=_v7ksOgFn-w' )
請(qǐng)記住,負(fù)責(zé)任地下載!
16. 創(chuàng)建隨機(jī)強(qiáng)密碼
使用此腳本生成強(qiáng)隨機(jī)密碼:
import string
import random
def generate_password(length):
chars = string.ascii_letters + string.digits + string.punctuation
return ''.join(random.choice(chars) for _ in range(length))
print(generate_password(16))
再也不用為想個(gè)密碼而頭疼了。
17. 獲取實(shí)時(shí)股票價(jià)格
使用此快速腳本跟蹤實(shí)時(shí)股票價(jià)格:
import requests
def get_stock_price(symbol):
url = f"https://finnhub.io/api/v1/quote?symbol={symbol}&token=your_api_key"
response = requests.get(url)
data = response.json()
return data['c']
print(get_stock_price('AAPL'))
實(shí)現(xiàn)了邊寫代碼,邊炒股了!
18. 創(chuàng)建一個(gè)簡(jiǎn)單的聊天機(jī)器人
制作自己的聊天機(jī)器人:
import random
def chatbot():
responses = ['Hello!', 'How can I help you?', 'Goodbye!']
while True:
user_input = input("You: ")
if user_input.lower() == 'bye':
print("Chatbot: Goodbye!")
break
print(f"Chatbot: {random.choice(responses)}")
chatbot()
你的個(gè)人助理,僅需幾行代碼即可創(chuàng)建。當(dāng)然,你也可以通過部署一個(gè)大語言模型為驅(qū)動(dòng),部署你的智能聊天機(jī)器人,只要你有足夠的顯卡資源。
19. 用計(jì)步器跟蹤每日步數(shù)
除了使用手表跟蹤步數(shù),作為一編程大佬,我們還可以使用 Python 獲取步數(shù):
import fitbit
def get_daily_steps(token):
client = fitbit.Fitbit('client_id', 'client_secret', oauth2_token=token)
steps = client.activities()['summary']['steps']
return steps
print(f"Steps today: {get_daily_steps('your_token')}")
Python 除了不能幫你生孩子,真實(shí)無所不能!
20. 創(chuàng)建待辦事項(xiàng)清單
一個(gè)簡(jiǎn)單的待辦事項(xiàng)清單,因?yàn)槲覀兊纳疃夹枰恍┲刃颍?/p>
import json
def add_task(task):
with open('todo.json', 'r+') as file:
tasks = json.load(file)
tasks.append(task)
file.seek(0)
json.dump(tasks, file)
add_task('Publish Medium article')
以 Pythonic 方式掌握最新動(dòng)態(tài)。