用 Python 優(yōu)化日常任務(wù)的 19 個(gè)妙招
1. 快速批量重命名文件
有時(shí)候我們需要一次性更改大量文件的名字,比如整理照片或文檔時(shí)。Python可以輕松搞定這個(gè)任務(wù)。
import os
# 設(shè)置文件夾路徑
folder_path = 'C:/Users/YourName/Documents/'
# 獲取文件夾中所有文件名
files = os.listdir(folder_path)
# 為每個(gè)文件重命名
for index, file in enumerate(files):
# 獲取文件擴(kuò)展名
extension = os.path.splitext(file)[1]
# 生成新文件名
new_name = f"file_{index}{extension}"
# 構(gòu)建完整路徑
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)
說(shuō)明:這段代碼會(huì)將指定文件夾中的所有文件按順序重新命名為file_0.jpg, file_1.pdf等格式。
2. 自動(dòng)下載網(wǎng)頁(yè)上的圖片
假設(shè)你在瀏覽一個(gè)網(wǎng)頁(yè),發(fā)現(xiàn)上面有很多漂亮的圖片想要保存下來(lái)。手動(dòng)一張張保存太麻煩了,不如用Python來(lái)自動(dòng)下載。
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)
說(shuō)明:這段腳本會(huì)訪問(wèn)指定URL,解析HTML文檔找到所有圖片鏈接,并將其下載到本地目錄中。
3. 使用正則表達(dá)式提取信息
正則表達(dá)式是處理文本的強(qiáng)大工具。比如,你可以用它從郵件地址列表中提取所有的郵箱地址。
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']
說(shuō)明:這里使用了正則表達(dá)式匹配常見(jiàn)的電子郵件格式。
4. 自動(dòng)生成Excel報(bào)告
工作中經(jīng)常需要制作報(bào)表,如果能自動(dòng)生成Excel表格,那該多好?。?/p>
import pandas as pd
data = {
'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35],
'City': ['New York', 'Los Angeles', 'Chicago']
}
df = pd.DataFrame(data)
# 創(chuàng)建Excel writer對(duì)象
writer = pd.ExcelWriter('report.xlsx', engine='xlsxwriter')
# 將DataFrame寫(xiě)入Excel
df.to_excel(writer, sheet_name='Sheet1', index=False)
# 保存Excel文件
writer.save()
說(shuō)明:這段代碼創(chuàng)建了一個(gè)包含三列數(shù)據(jù)的DataFrame,并將其導(dǎo)出為名為report.xlsx的Excel文件。
5. 通過(guò)發(fā)送電子郵件提醒自己
有些重要的事情容易忘記?讓Python幫你發(fā)送郵件提醒吧!
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()
)
說(shuō)明:此腳本允許用戶通過(guò)輸入密碼的方式安全地發(fā)送帶有HTML格式內(nèi)容的電子郵件。
6. 批量壓縮文件
有時(shí)候我們需要將多個(gè)文件壓縮成一個(gè)歸檔文件,以方便傳輸或存儲(chǔ)。Python可以輕松完成這一任務(wù)。
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)
說(shuō)明:這段代碼將file1.txt, file2.txt, file3.txt這三個(gè)文件壓縮成一個(gè)名為archive.zip的歸檔文件。
7. 圖像處理與識(shí)別
圖像處理是一個(gè)非常實(shí)用的功能,特別是在社交媒體和攝影中。我們可以使用Python的Pillow庫(kù)來(lái)處理圖像。
from PIL import Image
# 打開(kāi)圖像文件
image = Image.open('input.jpg')
# 調(diào)整圖像大小
resized_image = image.resize((800, 600))
# 保存修改后的圖像
resized_image.save('output.jpg')
# 旋轉(zhuǎn)圖像
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')
說(shuō)明:這段代碼展示了如何調(diào)整圖像大小、旋轉(zhuǎn)圖像以及添加水印。
8. 數(shù)據(jù)清洗與預(yù)處理
在進(jìn)行數(shù)據(jù)分析之前,通常需要對(duì)數(shù)據(jù)進(jìn)行清洗和預(yù)處理。Python的pandas庫(kù)提供了強(qiáng)大的數(shù)據(jù)處理功能。
import pandas as pd
# 讀取CSV文件
data = pd.read_csv('data.csv')
# 查看前幾行數(shù)據(jù)
print(data.head())
# 刪除缺失值
data.dropna(inplace=True)
# 刪除重復(fù)行
data.drop_duplicates(inplace=True)
# 修改列名
data.rename(columns={'old_column_name': 'new_column_name'}, inplace=True)
# 保存處理后的數(shù)據(jù)
data.to_csv('cleaned_data.csv', index=False)
說(shuō)明:這段代碼展示了如何讀取CSV文件、刪除缺失值、刪除重復(fù)行以及修改列名。
9. 網(wǎng)頁(yè)爬蟲(chóng)
從網(wǎng)頁(yè)上抓取數(shù)據(jù)是一項(xiàng)常見(jiàn)任務(wù)。Python的requests和BeautifulSoup庫(kù)可以幫助我們輕松實(shí)現(xiàn)這一目標(biāo)。
import requests
from bs4 import BeautifulSoup
url = 'https://example.com'
response = requests.get(url)
# 解析HTML
soup = BeautifulSoup(response.text, 'html.parser')
# 提取標(biāo)題
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'))
說(shuō)明:這段代碼展示了如何獲取網(wǎng)頁(yè)標(biāo)題、提取所有段落內(nèi)容以及獲取所有鏈接。
10. 文本處理與分析
文本處理在自然語(yǔ)言處理中非常重要。Python的nltk庫(kù)提供了豐富的文本處理功能。
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)
# 詞頻統(tǒng)計(jì)
from collections import Counter
word_counts = Counter(filtered_words)
print(word_counts.most_common())
說(shuō)明:這段代碼展示了如何分詞、句子分割、移除停用詞以及統(tǒng)計(jì)詞頻。
11. Excel數(shù)據(jù)處理
Excel文件在日常工作中非常常見(jiàn)。Python的pandas庫(kù)可以輕松處理Excel文件。
import pandas as pd
# 讀取Excel文件
data = pd.read_excel('data.xlsx')
# 查看前幾行數(shù)據(jù)
print(data.head())
# 刪除缺失值
data.dropna(inplace=True)
# 計(jì)算總和
total = data['Amount'].sum()
print(f'Total: {total}')
# 保存處理后的數(shù)據(jù)
data.to_excel('processed_data.xlsx', index=False)
說(shuō)明:這段代碼展示了如何讀取Excel文件、刪除缺失值、計(jì)算總和以及保存處理后的數(shù)據(jù)。
12. 日志記錄與調(diào)試
在編寫(xiě)程序時(shí),日志記錄是非常重要的。Python的logging模塊可以幫助我們記錄程序運(yùn)行過(guò)程中的信息。
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')
說(shuō)明:這段代碼展示了如何配置日志記錄并記錄不同級(jí)別的日志信息。
13. 數(shù)據(jù)可視化
數(shù)據(jù)可視化可以讓數(shù)據(jù)分析更加直觀。Python的matplotlib和seaborn庫(kù)提供了豐富的繪圖功能。
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
# 讀取數(shù)據(jù)
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()
# 繪制散點(diǎn)圖
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()
說(shuō)明:這段代碼展示了如何繪制柱狀圖、折線圖和散點(diǎn)圖。
14. PDF操作
PDF文件在很多場(chǎng)合都非常常用。Python的PyPDF2庫(kù)可以用來(lái)處理PDF文件。
import PyPDF2
# 讀取PDF文件
pdf_file = open('input.pdf', 'rb')
reader = PyPDF2.PdfReader(pdf_file)
# 獲取頁(yè)面數(shù)量
num_pages = len(reader.pages)
print(f'Number of pages: {num_pages}')
# 提取第一頁(yè)內(nèi)容
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)
# 寫(xiě)入新文件
output_pdf = open('output.pdf', 'wb')
pdf_writer.write(output_pdf)
# 關(guān)閉文件
pdf_file.close()
output_pdf.close()
說(shuō)明:這段代碼展示了如何讀取PDF文件、提取頁(yè)面內(nèi)容以及合并PDF文件。
15. 數(shù)據(jù)加密與解密
數(shù)據(jù)安全性非常重要。Python的cryptography庫(kù)可以用來(lái)加密和解密數(shù)據(jù)。
from cryptography.fernet import Fernet
# 生成密鑰
key = Fernet.generate_key()
cipher_suite = Fernet(key)
# 加密數(shù)據(jù)
plaintext = b"This is a secret message."
ciphertext = cipher_suite.encrypt(plaintext)
print(f'Ciphertext: {ciphertext}')
# 解密數(shù)據(jù)
decrypted_text = cipher_suite.decrypt(ciphertext)
print(f'Decrypted text: {decrypted_text.decode()}')
說(shuō)明:這段代碼展示了如何生成密鑰、加密數(shù)據(jù)以及解密數(shù)據(jù)。
16. 文件監(jiān)控與通知
監(jiān)控文件夾的變化并及時(shí)通知是非常有用的。Python的watchdog庫(kù)可以幫助我們實(shí)現(xiàn)這一功能。
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!')
# 設(shè)置觀察器
observer = Observer()
observer.schedule(MyHandler(), path='C:/Users/YourName/Documents/', recursive=True)
observer.start()
try:
while True:
pass
except KeyboardInterrupt:
observer.stop()
observer.join()
說(shuō)明:這段代碼展示了如何設(shè)置文件夾監(jiān)控并在文件發(fā)生變化時(shí)打印通知。
17. 自動(dòng)化辦公任務(wù)
自動(dòng)化辦公任務(wù)可以大大提高工作效率。Python可以用來(lái)自動(dòng)化Excel、Word等辦公軟件的操作。
import win32com.client
# 創(chuàng)建Excel應(yīng)用程序?qū)ο?excel = win32com.client.Dispatch("Excel.Application")
excel.Visible = True
# 新建一個(gè)工作簿
workbook = excel.Workbooks.Add()
# 在單元格中寫(xiě)入數(shù)據(jù)
worksheet = workbook.Worksheets(1)
worksheet.Cells(1, 1).Value = "Hello, World!"
# 保存工作簿
workbook.SaveAs("C:/Users/YourName/Documents/automated_workbook.xlsx")
# 關(guān)閉工作簿
workbook.Close(SaveChanges=True)
# 關(guān)閉Excel應(yīng)用程序
excel.Application.Quit()
說(shuō)明:這段代碼展示了如何創(chuàng)建Excel應(yīng)用程序?qū)ο?、新建工作簿、?xiě)入數(shù)據(jù)并保存。
18. 自動(dòng)化郵件發(fā)送
自動(dòng)化郵件發(fā)送可以在特定時(shí)間發(fā)送郵件,提高工作效率。
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
# 創(chuàng)建純文本和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消息轉(zhuǎn)換為MIMEText對(duì)象
part1 = MIMEText(text, "plain")
part2 = MIMEText(html, "html")
# 將純文本和HTML消息附加到MIMEMultipart消息
message.attach(part1)
message.attach(part2)
# 創(chuàng)建安全連接并發(fā)送郵件
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())
說(shuō)明:這段代碼展示了如何創(chuàng)建純文本和HTML版本的消息并發(fā)送郵件。
19. 實(shí)戰(zhàn)案例:自動(dòng)化數(shù)據(jù)分析流程
假設(shè)你是一名數(shù)據(jù)分析師,每天需要處理大量的銷(xiāo)售數(shù)據(jù)。我們可以使用Python自動(dòng)化整個(gè)數(shù)據(jù)分析流程。
- 讀取數(shù)據(jù)
- 數(shù)據(jù)清洗
- 數(shù)據(jù)處理
- 數(shù)據(jù)可視化
- 發(fā)送報(bào)告
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
# 創(chuàng)建純文本和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消息轉(zhuǎn)換為MIMEText對(duì)象
part1 = MIMEText(text, "plain")
part2 = MIMEText(html, "html")
# 將純文本和HTML消息附加到MIMEMultipart消息
message.attach(part1)
message.attach(part2)
# 創(chuàng)建安全連接并發(fā)送郵件
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())
說(shuō)明:這段代碼展示了如何讀取銷(xiāo)售數(shù)據(jù)、進(jìn)行數(shù)據(jù)清洗、數(shù)據(jù)處理、數(shù)據(jù)可視化并將結(jié)果發(fā)送給指定的郵箱。