python实际应用场景代码

1. 自动化文件整理

import os
import shutil

def organize_downloads_folder():
    download_path = "/Users/YourName/Downloads"  # 修改为你的下载路径
    file_types = {
        "Images": [".jpg", ".png", ".gif"],
        "Documents": [".pdf", ".docx", ".txt"],
        "Videos": [".mp4", ".mov"],
        "Music": [".mp3", ".wav"]
    }

    for filename in os.listdir(download_path):
        file_path = os.path.join(download_path, filename)
        if os.path.isfile(file_path):
            file_ext = os.path.splitext(filename)[1].lower()
            for folder, extensions in file_types.items():
                if file_ext in extensions:
                    dest_folder = os.path.join(download_path, folder)
                    if not os.path.exists(dest_folder):
                        os.makedirs(dest_folder)
                    shutil.move(file_path, dest_folder)
                    break

organize_downloads_folder()

2. 定时提醒工具

使用 schedule 库实现定时提醒:

import schedule
import time
from datetime import datetime

def drink_water_reminder():
    current_time = datetime.now().strftime("%H:%M:%S")
    print(f"[{current_time}] 该喝水啦!")

# 每2小时提醒一次
schedule.every(2).hours.do(drink_water_reminder)

while True:
    schedule.run_pending()
    time.sleep(1)

3. 天气查询工具

通过 API 获取实时天气(需注册 OpenWeatherMap 获取 API Key):

import requests

def get_weather(city, api_key):
    base_url = "http://api.openweathermap.org/data/2.5/weather"
    params = {
        "q": city,
        "appid": api_key,
        "units": "metric"
    }
    response = requests.get(base_url, params=params)
    data = response.json()
    if data["cod"] == 200:
        temp = data["main"]["temp"]
        desc = data["weather"][0]["description"]
        print(f"{city}天气:{desc},温度 {temp}°C")
    else:
        print("查询失败")

# 使用示例
get_weather("Beijing", "your_api_key_here")

4. 待办事项管理

使用 sqlite3 创建本地待办事项:

import sqlite3

def create_todo_table():
    conn = sqlite3.connect('todo.db')
    c = conn.cursor()
    c.execute('''CREATE TABLE IF NOT EXISTS todos
                 (id INTEGER PRIMARY KEY, task TEXT, done BOOLEAN)''')
    conn.commit()
    conn.close()

def add_todo(task):
    conn = sqlite3.connect('todo.db')
    c = conn.cursor()
    c.execute("INSERT INTO todos (task, done) VALUES (?, ?)", (task, False))
    conn.commit()
    conn.close()

def show_todos():
    conn = sqlite3.connect('todo.db')
    c = conn.cursor()
    c.execute("SELECT id, task FROM todos WHERE done = 0")
    todos = c.fetchall()
    for todo in todos:
        print(f"{todo[0]}. {todo[1]}")
    conn.close()

# 使用示例
create_todo_table()
add_todo("购买 groceries")
add_todo("完成工作报告")
show_todos()

5. 家庭财务跟踪

使用 pandas 分析 CSV 格式的消费记录:

import pandas as pd

def analyze_expenses(csv_path):
    df = pd.read_csv(csv_path)
    df['Date'] = pd.to_datetime(df['Date'])
    
    # 按月份统计支出
    monthly_expenses = df.groupby(df['Date'].dt.month)['Amount'].sum()
    print("月度支出统计:\n", monthly_expenses)
    
    # 按类别统计
    category_expenses = df.groupby('Category')['Amount'].sum()
    print("\n分类支出统计:\n", category_expenses)

# CSV 示例格式:
# Date,Category,Amount,Description
# 2023-01-01,Food,50.0,Supermarket
analyze_expenses("expenses.csv")

6. 自动化邮件发送

使用 smtplib 发送邮件:

import smtplib
from email.mime.text import MIMEText

def send_email(subject, body, to_email):
    sender_email = "[email protected]"
    sender_password = "your_app_password"  # Gmail需使用应用专用密码
    
    msg = MIMEText(body)
    msg['Subject'] = subject
    msg['From'] = sender_email
    msg['To'] = to_email
    
    with smtplib.SMTP_SSL('smtp.gmail.com', 465) as server:
        server.login(sender_email, sender_password)
        server.send_message(msg)
        print("邮件发送成功!")

# 使用示例
send_email("每日报告", "今日任务已完成!", "[email protected]")

以下是开源的推荐

  1. Home Assistant

    • 家庭自动化平台: Home Assistant

  2. Invoice Generator

    • 自动化生成发票: https://github.com/InvoiceGenerator/invoicegenerator

  3. Personal Finance Tools

    • 个人财务工具集合: GitHub - beancount/beancount: Beancount: Double-Entry Accounting from Text Files.

    • python实际应用场景代码_第1张图片

你可能感兴趣的:(python,前端,服务器)