分享10个Python代码片段
2024 年 10 月,Python 继续蝉联最受欢迎编程语言的宝座,在过去一个月中增长了 +7.08%,占据了 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、发送电子邮件,最喜欢的话题的最新 Reddit 帖子
如果对某个特定的 reddit 情有独钟,但又不想不断地查看它,下面这个 Python 脚本,可以将最新的帖子直接发送到邮箱:
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、将网页转换为电子书
下面这个 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、检查网站可用性
想知道网站是否宕机?这里有一个简单的脚本可以检查:
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'))
基于上面的代码片段进行延续,如发送邮箱或者通知等等。
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、创建一个简单的聊天机器人
制作你自己的聊天机器人:
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、生成二维码
为任何网址或文本创建二维码:
import qrcode
def generate_qr(text, filename):
img = qrcode.make(text)
img.save(f"{filename}.png")
generate_qr('https://example.com', 'my_qr_code')