偷偷摘套内射激情视频,久久精品99国产国产精,中文字幕无线乱码人妻,中文在线中文a,性爽19p

用 Python 優(yōu)化日常任務(wù)的 19 個妙招

開發(fā)
有時候我們需要一次性更改大量文件的名字,比如整理照片或文檔時,Python可以輕松搞定這個任務(wù)。

1. 快速批量重命名文件

有時候我們需要一次性更改大量文件的名字,比如整理照片或文檔時。Python可以輕松搞定這個任務(wù)。

import os

# 設(shè)置文件夾路徑
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}"
    # 構(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)

說明:這段代碼會將指定文件夾中的所有文件按順序重新命名為file_0.jpg, file_1.pdf等格式。

2. 自動下載網(wǎng)頁上的圖片

假設(shè)你在瀏覽一個網(wǎng)頁,發(fā)現(xiàn)上面有很多漂亮的圖片想要保存下來。手動一張張保存太麻煩了,不如用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報告

工作中經(jīng)常需要制作報表,如果能自動生成Excel表格,那該多好??!

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對象
writer = pd.ExcelWriter('report.xlsx', engine='xlsxwriter')

# 將DataFrame寫入Excel
df.to_excel(writer, sheet_name='Sheet1', index=False)

# 保存Excel文件
writer.save()

說明:這段代碼創(chuàng)建了一個包含三列數(shù)據(jù)的DataFrame,并將其導(dǎo)出為名為report.xlsx的Excel文件。

5. 通過發(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()
    )

說明:此腳本允許用戶通過輸入密碼的方式安全地發(fā)送帶有HTML格式內(nèi)容的電子郵件。

6. 批量壓縮文件

有時候我們需要將多個文件壓縮成一個歸檔文件,以方便傳輸或存儲。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)

說明:這段代碼將file1.txt, file2.txt, file3.txt這三個文件壓縮成一個名為archive.zip的歸檔文件。

7. 圖像處理與識別

圖像處理是一個非常實用的功能,特別是在社交媒體和攝影中。我們可以使用Python的Pillow庫來處理圖像。

from PIL import Image

# 打開圖像文件
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')

說明:這段代碼展示了如何調(diào)整圖像大小、旋轉(zhuǎn)圖像以及添加水印。

8. 數(shù)據(jù)清洗與預(yù)處理

在進行數(shù)據(jù)分析之前,通常需要對數(shù)據(jù)進行清洗和預(yù)處理。Python的pandas庫提供了強大的數(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)

說明:這段代碼展示了如何讀取CSV文件、刪除缺失值、刪除重復(fù)行以及修改列名。

9. 網(wǎng)頁爬蟲

從網(wǎng)頁上抓取數(shù)據(jù)是一項常見任務(wù)。Python的requests和BeautifulSoup庫可以幫助我們輕松實現(xiàn)這一目標。

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'))

說明:這段代碼展示了如何獲取網(wǎng)頁標題、提取所有段落內(nèi)容以及獲取所有鏈接。

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)

# 詞頻統(tǒng)計
from collections import Counter
word_counts = Counter(filtered_words)
print(word_counts.most_common())

說明:這段代碼展示了如何分詞、句子分割、移除停用詞以及統(tǒng)計詞頻。

11. Excel數(shù)據(jù)處理

Excel文件在日常工作中非常常見。Python的pandas庫可以輕松處理Excel文件。

import pandas as pd

# 讀取Excel文件
data = pd.read_excel('data.xlsx')

# 查看前幾行數(shù)據(jù)
print(data.head())

# 刪除缺失值
data.dropna(inplace=True)

# 計算總和
total = data['Amount'].sum()
print(f'Total: {total}')

# 保存處理后的數(shù)據(jù)
data.to_excel('processed_data.xlsx', index=False)

說明:這段代碼展示了如何讀取Excel文件、刪除缺失值、計算總和以及保存處理后的數(shù)據(jù)。

12. 日志記錄與調(diào)試

在編寫程序時,日志記錄是非常重要的。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. 數(shù)據(jù)可視化

數(shù)據(jù)可視化可以讓數(shù)據(jù)分析更加直觀。Python的matplotlib和seaborn庫提供了豐富的繪圖功能。

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()

# 繪制散點圖
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)

# 獲取頁面數(shù)量
num_pages = len(reader.pages)
print(f'Number of pages: {num_pages}')

# 提取第一頁內(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)

# 寫入新文件
output_pdf = open('output.pdf', 'wb')
pdf_writer.write(output_pdf)

# 關(guān)閉文件
pdf_file.close()
output_pdf.close()

說明:這段代碼展示了如何讀取PDF文件、提取頁面內(nèi)容以及合并PDF文件。

15. 數(shù)據(jù)加密與解密

數(shù)據(jù)安全性非常重要。Python的cryptography庫可以用來加密和解密數(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()}')

說明:這段代碼展示了如何生成密鑰、加密數(shù)據(jù)以及解密數(shù)據(jù)。

16. 文件監(jiān)控與通知

監(jiān)控文件夾的變化并及時通知是非常有用的。Python的watchdog庫可以幫助我們實現(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()

說明:這段代碼展示了如何設(shè)置文件夾監(jiān)控并在文件發(fā)生變化時打印通知。

17. 自動化辦公任務(wù)

自動化辦公任務(wù)可以大大提高工作效率。Python可以用來自動化Excel、Word等辦公軟件的操作。

import win32com.client

# 創(chuàng)建Excel應(yīng)用程序?qū)ο?excel = win32com.client.Dispatch("Excel.Application")
excel.Visible = True

# 新建一個工作簿
workbook = excel.Workbooks.Add()

# 在單元格中寫入數(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()

說明:這段代碼展示了如何創(chuàng)建Excel應(yīng)用程序?qū)ο?、新建工作簿、寫入?shù)據(jù)并保存。

18. 自動化郵件發(fā)送

自動化郵件發(fā)送可以在特定時間發(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對象
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())

說明:這段代碼展示了如何創(chuàng)建純文本和HTML版本的消息并發(fā)送郵件。

19. 實戰(zhàn)案例:自動化數(shù)據(jù)分析流程

假設(shè)你是一名數(shù)據(jù)分析師,每天需要處理大量的銷售數(shù)據(jù)。我們可以使用Python自動化整個數(shù)據(jù)分析流程。

  • 讀取數(shù)據(jù)
  • 數(shù)據(jù)清洗
  • 數(shù)據(jù)處理
  • 數(shù)據(jù)可視化
  • 發(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對象
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())

說明:這段代碼展示了如何讀取銷售數(shù)據(jù)、進行數(shù)據(jù)清洗、數(shù)據(jù)處理、數(shù)據(jù)可視化并將結(jié)果發(fā)送給指定的郵箱。

責任編輯:趙寧寧 來源: 小白PythonAI編程
相關(guān)推薦

2024-08-14 14:42:00

2024-07-01 18:07:30

Python腳本自動化

2022-10-09 14:50:44

Python腳本

2023-11-10 09:32:23

Python文件操作

2025-02-19 10:35:57

2021-04-01 06:13:50

Ansible系統(tǒng)運維

2025-07-03 07:20:00

Python腳本編程語言

2009-04-02 10:59:57

優(yōu)化插入MySQL

2021-04-16 08:11:07

程序體積優(yōu)化

2017-12-13 09:53:57

程序員編程編碼

2024-08-12 10:03:08

2019-12-04 15:08:04

AWS亞馬遜機器學習

2009-10-13 14:53:00

2017-06-02 13:22:51

WiFi優(yōu)化無線路由器

2023-01-05 13:36:41

Script優(yōu)化任務(wù)

2017-06-12 17:54:45

Python編程

2010-07-01 14:18:09

SQL Server數(shù)

2024-12-26 07:47:05

Spring管理配置

2023-04-14 18:02:09

2017-06-01 14:13:15

圖片優(yōu)化PSSEO
點贊
收藏

51CTO技術(shù)棧公眾號