分享10個Python代碼片段

2024 年 10 月,Python 繼續(xù)蟬聯(lián)最受歡迎編程語言的寶座,在過去一個月中增長了 +7.08%,占據(jù)了 21.90% 的市場份額。如果渴望一些能讓你看起來像編程高手的腳本,那就不要錯過本文的精彩內容,從中也能學習到 Python 的一些精髓。
1、文件重復查找器
有沒有看過你的硬盤,想過,為什么只剩下 100MB 了? 重復文件,大概率是因為這個原因。在這里有一個腳本可以找到重復文件并刪除它們:
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')
2、自動整理下載文件夾
下面這個腳本可以幫你整理下載文件夾:
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')
通常情況下沒有人有時間去手動整理文件。
3、批量圖像調整器
是否正在進行一個需要圖像調整大小的項目嗎?下面的腳本可以輕松幫您批量調整圖片的大小:
from PIL import Image
import os
def batch_resize(folder, width, height):
for filename in os.listdir(folder):
if filename.endswith(('.jpeg', '.jpg', '.png')):
img = Image.open(os.path.join(folder, filename))
img = img.resize((width, height))
img.save(os.path.join(folder, f"resized_{filename}"))
print(f'Resized {filename}')
batch_resize('/path/to/images', 800, 600)
4、發(fā)送電子郵件,最喜歡的話題的最新 Reddit 帖子
如果對某個特定的 reddit 情有獨鐘,但又不想不斷地查看它,下面這個 Python 腳本,可以將最新的帖子直接發(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))
5、將網(wǎng)頁轉換為電子書
下面這個 Python 腳本可以將最喜歡的文章轉換為電子書格式,非常適合離線閱讀:
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')
6、將文本轉換為語音
有沒有覺得想聽你的代碼輸出而不是閱讀它?這個腳本將文本轉換為語音:
import pyttsx3
def text_to_speech(text):
engine = pyttsx3.init()
engine.say(text)
engine.runAndWait()
text_to_speech('Hello World, Python is amazing!')
7、檢查網(wǎng)站可用性
想知道網(wǎng)站是否宕機?這里有一個簡單的腳本可以檢查:
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'))
基于上面的代碼片段進行延續(xù),如發(fā)送郵箱或者通知等等。
8、將 PDF 轉換為文本
如果經常處理 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'))
9、創(chuàng)建一個簡單的聊天機器人
制作你自己的聊天機器人:
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()
10、生成二維碼
為任何網(wǎng)址或文本創(chuàng)建二維碼:
import qrcode
def generate_qr(text, filename):
img = qrcode.make(text)
img.save(f"{filename}.png")
generate_qr('https://example.com', 'my_qr_code')