用 Python 優化日常任務的 19 個妙招
1. 快速批量重命名文件
有時候我們需要一次性更改大量文件的名字,比如整理照片或文檔時。Python可以輕松搞定這個任務。
import os
# 設置文件夾路徑
folder_path = 'C:/Users/YourName/Documents/'
# 獲取文件夾中所有文件名
files = os.listdir(folder_path)
# 為每個文件重命名
for index, file in enumerate(files):
# 獲取文件擴展名
extension = os.path.splitext(file)[1]
# 生成新文件名
new_name = f"file_{index}{extension}"
# 構建完整路徑
old_file_path = os.path.join(folder_path, file)
new_file_path = os.path.join(folder_path, new_name)
# 重命名文件
os.rename(old_file_path, new_file_path)
說明:這段代碼會將指定文件夾中的所有文件按順序重新命名為file_0.jpg, file_1.pdf等格式。
2. 自動下載網頁上的圖片
假設你在瀏覽一個網頁,發現上面有很多漂亮的圖片想要保存下來。手動一張張保存太麻煩了,不如用Python來自動下載。
import requests
from bs4 import BeautifulSoup
import os
url = 'https://example.com'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
images = soup.find_all('img')
folder_path = 'C:/Users/YourName/Pictures/'
if not os.path.exists(folder_path):
os.makedirs(folder_path)
for image in images:
src = image.get('src')
if src.startswith('http'):
img_data = requests.get(src).content
filename = os.path.join(folder_path, src.split('/')[-1])
with open(filename, 'wb') as f:
f.write(img_data)
說明:這段腳本會訪問指定URL,解析HTML文檔找到所有圖片鏈接,并將其下載到本地目錄中。
3. 使用正則表達式提取信息
正則表達式是處理文本的強大工具。比如,你可以用它從郵件地址列表中提取所有的郵箱地址。
import re
text = '''
Hello,
My email is example@email.com and my friend's email is another@example.org.
Please contact us at your convenience.
'''
emails = re.findall(r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b', text)
print(emails) # 輸出: ['example@email.com', 'another@example.org']
說明:這里使用了正則表達式匹配常見的電子郵件格式。
4. 自動生成Excel報告
工作中經常需要制作報表,如果能自動生成Excel表格,那該多好啊!
import pandas as pd
data = {
'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35],
'City': ['New York', 'Los Angeles', 'Chicago']
}
df = pd.DataFrame(data)
# 創建Excel writer對象
writer = pd.ExcelWriter('report.xlsx', engine='xlsxwriter')
# 將DataFrame寫入Excel
df.to_excel(writer, sheet_name='Sheet1', index=False)
# 保存Excel文件
writer.save()
說明:這段代碼創建了一個包含三列數據的DataFrame,并將其導出為名為report.xlsx的Excel文件。
5. 通過發送電子郵件提醒自己
有些重要的事情容易忘記?讓Python幫你發送郵件提醒吧!
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
sender_email = "your_email@example.com"
receiver_email = "receiver_email@example.com"
password = input("Type your password and press enter:")
message = MIMEMultipart("alternative")
message["Subject"] = "Python Email Reminder"
message["From"] = sender_email
message["To"] = receiver_email
# Create the plain-text and HTML version of your message
text = """\
Hi,
How are you?
Real Python has many great tutorials:
www.realpython.com"""
html = """\
<html>
<body>
<p>Hi,<br>
How are you?<br>
<a >Real Python</a>
has many great tutorials.
</p>
</body>
</html>
"""
# Turn these into plain/html MIMEText objects
part1 = MIMEText(text, "plain")
part2 = MIMEText(html, "html")
# Add HTML/plain-text parts to MIMEMultipart message
# The email client will try to render the last part first
message.attach(part1)
message.attach(part2)
# Create secure connection with server and send email
context = ssl.create_default_context()
with smtplib.SMTP_SSL("smtp.gmail.com", 465, context=context) as server:
server.login(sender_email, password)
server.sendmail(
sender_email, receiver_email, message.as_string()
)
說明:此腳本允許用戶通過輸入密碼的方式安全地發送帶有HTML格式內容的電子郵件。
6. 批量壓縮文件
有時候我們需要將多個文件壓縮成一個歸檔文件,以方便傳輸或存儲。Python可以輕松完成這一任務。
import zipfile
import os
def zip_files(zip_filename, files):
with zipfile.ZipFile(zip_filename, 'w', zipfile.ZIP_DEFLATED) as zipf:
for file in files:
zipf.write(file)
# 指定要壓縮的文件列表
files_to_zip = ['file1.txt', 'file2.txt', 'file3.txt']
# 指定壓縮后的文件名
zip_filename = 'archive.zip'
# 壓縮文件
zip_files(zip_filename, files_to_zip)
說明:這段代碼將file1.txt, file2.txt, file3.txt這三個文件壓縮成一個名為archive.zip的歸檔文件。
7. 圖像處理與識別
圖像處理是一個非常實用的功能,特別是在社交媒體和攝影中。我們可以使用Python的Pillow庫來處理圖像。
from PIL import Image
# 打開圖像文件
image = Image.open('input.jpg')
# 調整圖像大小
resized_image = image.resize((800, 600))
# 保存修改后的圖像
resized_image.save('output.jpg')
# 旋轉圖像
rotated_image = image.rotate(90)
rotated_image.save('rotated_output.jpg')
# 添加水印
watermark = Image.open('watermark.png')
watermark = watermark.resize((100, 100))
position = (image.width - watermark.width, image.height - watermark.height)
image.paste(watermark, position, mask=watermark)
image.save('watermarked_output.jpg')
說明:這段代碼展示了如何調整圖像大小、旋轉圖像以及添加水印。
8. 數據清洗與預處理
在進行數據分析之前,通常需要對數據進行清洗和預處理。Python的pandas庫提供了強大的數據處理功能。
import pandas as pd
# 讀取CSV文件
data = pd.read_csv('data.csv')
# 查看前幾行數據
print(data.head())
# 刪除缺失值
data.dropna(inplace=True)
# 刪除重復行
data.drop_duplicates(inplace=True)
# 修改列名
data.rename(columns={'old_column_name': 'new_column_name'}, inplace=True)
# 保存處理后的數據
data.to_csv('cleaned_data.csv', index=False)
說明:這段代碼展示了如何讀取CSV文件、刪除缺失值、刪除重復行以及修改列名。
9. 網頁爬蟲
從網頁上抓取數據是一項常見任務。Python的requests和BeautifulSoup庫可以幫助我們輕松實現這一目標。
import requests
from bs4 import BeautifulSoup
url = 'https://example.com'
response = requests.get(url)
# 解析HTML
soup = BeautifulSoup(response.text, 'html.parser')
# 提取標題
title = soup.title.string
print(f'Title: {title}')
# 提取所有段落
paragraphs = soup.find_all('p')
for p in paragraphs:
print(p.get_text())
# 提取所有鏈接
links = soup.find_all('a')
for link in links:
print(link.get('href'))
說明:這段代碼展示了如何獲取網頁標題、提取所有段落內容以及獲取所有鏈接。
10. 文本處理與分析
文本處理在自然語言處理中非常重要。Python的nltk庫提供了豐富的文本處理功能。
import nltk
from nltk.tokenize import word_tokenize, sent_tokenize
from nltk.corpus import stopwords
# 下載停用詞
nltk.download('punkt')
nltk.download('stopwords')
text = """
Python is a high-level programming language designed to be easy to read and simple to implement. It is widely used for web development as well as data analysis.
"""
# 分詞
words = word_tokenize(text)
print(words)
# 句子分割
sentences = sent_tokenize(text)
print(sentences)
# 移除停用詞
stop_words = set(stopwords.words('english'))
filtered_words = [word for word in words if word.lower() not in stop_words]
print(filtered_words)
# 詞頻統計
from collections import Counter
word_counts = Counter(filtered_words)
print(word_counts.most_common())
說明:這段代碼展示了如何分詞、句子分割、移除停用詞以及統計詞頻。
11. Excel數據處理
Excel文件在日常工作中非常常見。Python的pandas庫可以輕松處理Excel文件。
import pandas as pd
# 讀取Excel文件
data = pd.read_excel('data.xlsx')
# 查看前幾行數據
print(data.head())
# 刪除缺失值
data.dropna(inplace=True)
# 計算總和
total = data['Amount'].sum()
print(f'Total: {total}')
# 保存處理后的數據
data.to_excel('processed_data.xlsx', index=False)
說明:這段代碼展示了如何讀取Excel文件、刪除缺失值、計算總和以及保存處理后的數據。
12. 日志記錄與調試
在編寫程序時,日志記錄是非常重要的。Python的logging模塊可以幫助我們記錄程序運行過程中的信息。
import logging
# 配置日志記錄
logging.basicConfig(filename='app.log', level=logging.INFO)
# 記錄日志
logging.info('This is an info message')
logging.warning('This is a warning message')
logging.error('This is an error message')
說明:這段代碼展示了如何配置日志記錄并記錄不同級別的日志信息。
13. 數據可視化
數據可視化可以讓數據分析更加直觀。Python的matplotlib和seaborn庫提供了豐富的繪圖功能。
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
# 讀取數據
data = pd.read_csv('data.csv')
# 繪制柱狀圖
plt.figure(figsize=(10, 6))
sns.barplot(x='Category', y='Value', data=data)
plt.title('Bar Plot')
plt.xlabel('Category')
plt.ylabel('Value')
plt.show()
# 繪制折線圖
plt.figure(figsize=(10, 6))
sns.lineplot(x='Date', y='Sales', data=data)
plt.title('Line Plot')
plt.xlabel('Date')
plt.ylabel('Sales')
plt.show()
# 繪制散點圖
plt.figure(figsize=(10, 6))
sns.scatterplot(x='X', y='Y', data=data)
plt.title('Scatter Plot')
plt.xlabel('X')
plt.ylabel('Y')
plt.show()
說明:這段代碼展示了如何繪制柱狀圖、折線圖和散點圖。
14. PDF操作
PDF文件在很多場合都非常常用。Python的PyPDF2庫可以用來處理PDF文件。
import PyPDF2
# 讀取PDF文件
pdf_file = open('input.pdf', 'rb')
reader = PyPDF2.PdfReader(pdf_file)
# 獲取頁面數量
num_pages = len(reader.pages)
print(f'Number of pages: {num_pages}')
# 提取第一頁內容
page = reader.pages[0]
text = page.extract_text()
print(f'First page content:\n{text}')
# 合并PDF文件
pdf_writer = PyPDF2.PdfWriter()
for page_num in range(num_pages):
page = reader.pages[page_num]
pdf_writer.add_page(page)
# 寫入新文件
output_pdf = open('output.pdf', 'wb')
pdf_writer.write(output_pdf)
# 關閉文件
pdf_file.close()
output_pdf.close()
說明:這段代碼展示了如何讀取PDF文件、提取頁面內容以及合并PDF文件。
15. 數據加密與解密
數據安全性非常重要。Python的cryptography庫可以用來加密和解密數據。
from cryptography.fernet import Fernet
# 生成密鑰
key = Fernet.generate_key()
cipher_suite = Fernet(key)
# 加密數據
plaintext = b"This is a secret message."
ciphertext = cipher_suite.encrypt(plaintext)
print(f'Ciphertext: {ciphertext}')
# 解密數據
decrypted_text = cipher_suite.decrypt(ciphertext)
print(f'Decrypted text: {decrypted_text.decode()}')
說明:這段代碼展示了如何生成密鑰、加密數據以及解密數據。
16. 文件監控與通知
監控文件夾的變化并及時通知是非常有用的。Python的watchdog庫可以幫助我們實現這一功能。
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
class MyHandler(FileSystemEventHandler):
def on_modified(self, event):
print(f'Event type: {event.event_type} path : {event.src_path}')
print('File modified!')
# 設置觀察器
observer = Observer()
observer.schedule(MyHandler(), path='C:/Users/YourName/Documents/', recursive=True)
observer.start()
try:
while True:
pass
except KeyboardInterrupt:
observer.stop()
observer.join()
說明:這段代碼展示了如何設置文件夾監控并在文件發生變化時打印通知。
17. 自動化辦公任務
自動化辦公任務可以大大提高工作效率。Python可以用來自動化Excel、Word等辦公軟件的操作。
import win32com.client
# 創建Excel應用程序對象
excel = win32com.client.Dispatch("Excel.Application")
excel.Visible = True
# 新建一個工作簿
workbook = excel.Workbooks.Add()
# 在單元格中寫入數據
worksheet = workbook.Worksheets(1)
worksheet.Cells(1, 1).Value = "Hello, World!"
# 保存工作簿
workbook.SaveAs("C:/Users/YourName/Documents/automated_workbook.xlsx")
# 關閉工作簿
workbook.Close(SaveChanges=True)
# 關閉Excel應用程序
excel.Application.Quit()
說明:這段代碼展示了如何創建Excel應用程序對象、新建工作簿、寫入數據并保存。
18. 自動化郵件發送
自動化郵件發送可以在特定時間發送郵件,提高工作效率。
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
sender_email = "your_email@example.com"
receiver_email = "receiver_email@example.com"
password = input("Type your password and press enter:")
message = MIMEMultipart("alternative")
message["Subject"] = "Automated Email"
message["From"] = sender_email
message["To"] = receiver_email
# 創建純文本和HTML版本的消息
text = """\
Hi,
This is an automated email from Python.
"""
html = """\
<html>
<body>
<p>Hi,<br>
This is an automated email from Python.
</p>
</body>
</html>
"""
# 將純文本和HTML消息轉換為MIMEText對象
part1 = MIMEText(text, "plain")
part2 = MIMEText(html, "html")
# 將純文本和HTML消息附加到MIMEMultipart消息
message.attach(part1)
message.attach(part2)
# 創建安全連接并發送郵件
context = ssl.create_default_context()
with smtplib.SMTP_SSL("smtp.gmail.com", 465, context=context) as server:
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, message.as_string())
說明:這段代碼展示了如何創建純文本和HTML版本的消息并發送郵件。
19. 實戰案例:自動化數據分析流程
假設你是一名數據分析師,每天需要處理大量的銷售數據。我們可以使用Python自動化整個數據分析流程。
- 讀取數據
- 數據清洗
- 數據處理
- 數據可視化
- 發送報告
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
sender_email = "your_email@example.com"
receiver_email = "receiver_email@example.com"
password = input("Type your password and press enter:")
message = MIMEMultipart("alternative")
message["Subject"] = "Automated Email"
message["From"] = sender_email
message["To"] = receiver_email
# 創建純文本和HTML版本的消息
text = """\
Hi,
This is an automated email from Python.
"""
html = """\
<html>
<body>
<p>Hi,<br>
This is an automated email from Python.
</p>
</body>
</html>
"""
# 將純文本和HTML消息轉換為MIMEText對象
part1 = MIMEText(text, "plain")
part2 = MIMEText(html, "html")
# 將純文本和HTML消息附加到MIMEMultipart消息
message.attach(part1)
message.attach(part2)
# 創建安全連接并發送郵件
context = ssl.create_default_context()
with smtplib.SMTP_SSL("smtp.gmail.com", 465, context=context) as server:
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, message.as_string())
說明:這段代碼展示了如何讀取銷售數據、進行數據清洗、數據處理、數據可視化并將結果發送給指定的郵箱。