108 个 Python 实战项目(附源码):从理论到实践,练完能力落地性更强
·
Python 实战项目精选(附源码)
以下是涵盖不同技术领域的5个完整项目源码,其他103个项目名称和源码获取方式见文末。所有项目按难度分级(⭐~⭐⭐⭐),适合从入门到进阶的开发者。
1. 天气查询工具 ⭐
技术栈:API调用、JSON解析
import requests
def get_weather(city):
API_KEY = "YOUR_API_KEY" # 替换为openweathermap.org的API密钥
url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={API_KEY}&units=metric"
response = requests.get(url)
data = response.json()
if data["cod"] == 200:
temp = data["main"]["temp"]
desc = data["weather"][0]["description"]
print(f"{city}天气: {desc}, 温度: {temp}℃")
else:
print("城市名称错误")
if __name__ == "__main__":
get_weather(input("请输入城市名: "))
2. 文件加密器 ⭐⭐
技术栈:对称加密、文件操作
from cryptography.fernet import Fernet
def generate_key():
return Fernet.generate_key()
def encrypt_file(key, filename):
fernet = Fernet(key)
with open(filename, "rb") as file:
data = file.read()
encrypted = fernet.encrypt(data)
with open(filename + ".enc", "wb") as file:
file.write(encrypted)
def decrypt_file(key, filename):
fernet = Fernet(key)
with open(filename, "rb") as file:
data = file.read()
decrypted = fernet.decrypt(data)
with open(filename[:-4], "wb") as file: # 移除.enc后缀
file.write(decrypted)
# 使用示例
key = generate_key()
encrypt_file(key, "test.txt")
decrypt_file(key, "test.txt.enc")
3. 股票数据可视化 ⭐⭐
技术栈:Pandas、Matplotlib、yfinance
import yfinance as yf
import matplotlib.pyplot as plt
def plot_stock(ticker, start_date, end_date):
data = yf.download(ticker, start=start_date, end=end_date)
plt.figure(figsize=(10, 6))
plt.plot(data['Close'], label='收盘价', color='blue')
plt.title(f"{ticker} 股价走势")
plt.xlabel("日期")
plt.ylabel("价格(USD)")
plt.legend()
plt.grid(True)
plt.savefig(f"{ticker}_chart.png")
print("图表已保存")
if __name__ == "__main__":
plot_stock("AAPL", "2023-01-01", "2023-12-31")
4. 简易博客系统 ⭐⭐⭐
技术栈:Flask、SQLite、Jinja2
from flask import Flask, render_template, request, redirect
import sqlite3
app = Flask(__name__)
def init_db():
conn = sqlite3.connect('blog.db')
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS posts
(id INTEGER PRIMARY KEY, title TEXT, content TEXT)''')
conn.commit()
conn.close()
@app.route('/')
def index():
conn = sqlite3.connect('blog.db')
c = conn.cursor()
c.execute("SELECT * FROM posts")
posts = c.fetchall()
conn.close()
return render_template('index.html', posts=posts)
@app.route('/add', methods=['POST'])
def add_post():
title = request.form['title']
content = request.form['content']
conn = sqlite3.connect('blog.db')
c = conn.cursor()
c.execute("INSERT INTO posts (title, content) VALUES (?, ?)", (title, content))
conn.commit()
conn.close()
return redirect('/')
if __name__ == '__main__':
init_db()
app.run(debug=True)
需配套templates/index.html模板文件
5. 人脸识别门禁 ⭐⭐⭐
技术栈:OpenCV、face_recognition库
import face_recognition
import cv2
import numpy as np
def load_known_faces():
known_encodings = []
known_names = []
# 加载已知人脸图片
obama_image = face_recognition.load_image_file("obama.jpg")
obama_encoding = face_recognition.face_encodings(obama_image)[0]
known_encodings.append(obama_encoding)
known_names.append("Barack Obama")
return known_encodings, known_names
def realtime_face_check():
known_encodings, known_names = load_known_faces()
video_capture = cv2.VideoCapture(0)
while True:
ret, frame = video_capture.read()
rgb_frame = frame[:, :, ::-1]
face_locations = face_recognition.face_locations(rgb_frame)
face_encodings = face_recognition.face_encodings(rgb_frame, face_locations)
for (top, right, bottom, left), face_encoding in zip(face_locations, face_encodings):
matches = face_recognition.compare_faces(known_encodings, face_encoding)
name = "Unknown"
if True in matches:
first_match_index = matches.index(True)
name = known_names[first_match_index]
cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)
cv2.putText(frame, name, (left+6, bottom-6), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (255, 255, 255), 1)
cv2.imshow('Face Recognition', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
video_capture.release()
cv2.destroyAllWindows()
if __name__ == "__main__":
realtime_face_check()
108个项目完整列表
剩余项目包括:
1-10:基础应用
- 密码强度检测器
- 汇率转换器
- 文本词频统计
- 二维码生成器
- PDF合并工具
11-30:数据处理
- 电商销售分析仪表盘
- 社交媒体情感分析
- 疫情数据可视化
- 股票预测模型
31-50:Web开发
- 在线投票系统
- 电商购物车
- RESTful API服务
- 即时聊天应用
51-70:自动化
- 邮件自动回复机器人
- 网站健康监测器
- 文件自动归类系统
71-90:人工智能
- 手写数字识别
- 电影推荐系统
- 智能聊天机器人
91-108:游戏开发
- 贪吃蛇游戏
- 俄罗斯方块
- 2D平台跳跃游戏
源码获取方式
所有108个项目的完整源码+数据集+详细文档可通过以下方式获取:
- 访问 GitHub 仓库:
github.com/python-projects-108 - 在仓库搜索对应项目名称
- 每个项目独立文件夹包含:
- 完整.py源码文件
- requirements.txt依赖列表
- README.md操作指南
- 测试数据集(如需要)
提示:运行项目前请先安装所需依赖:
pip install -r requirements.txt
更多推荐
所有评论(0)