Python 综合实战项目

20.1 项目一:通讯录管理系统

功能需求

  • 添加联系人
  • 删除联系人
  • 查询联系人
  • 显示所有联系人
  • 保存到文件

实现代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import json
import os

class ContactManager:
def __init__(self, filename="contacts.json"):
self.filename = filename
self.contacts = self.load_contacts()

def load_contacts(self):
if os.path.exists(self.filename):
with open(self.filename, "r") as f:
return json.load(f)
return {}

def save_contacts(self):
with open(self.filename, "w") as f:
json.dump(self.contacts, f, indent=2, ensure_ascii=False)

def add_contact(self, name, phone, email):
if name in self.contacts:
print(f"联系人 {name} 已存在")
return
self.contacts[name] = {"phone": phone, "email": email}
self.save_contacts()
print(f"已添加: {name}")

def delete_contact(self, name):
if name in self.contacts:
del self.contacts[name]
self.save_contacts()
print(f"已删除: {name}")
else:
print(f"联系人 {name} 不存在")

def search_contact(self, name):
if name in self.contacts:
info = self.contacts[name]
print(f"姓名: {name}")
print(f"电话: {info['phone']}")
print(f"邮箱: {info['email']}")
else:
print(f"未找到: {name}")

def show_all(self):
if not self.contacts:
print("通讯录为空")
return
for name, info in self.contacts.items():
print(f"{name}: {info['phone']}, {info['email']}")

# 使用示例
manager = ContactManager()
manager.add_contact("Alice", "13800138000", "alice@example.com")
manager.add_contact("Bob", "13900139000", "bob@example.com")
manager.show_all()
manager.search_contact("Alice")

20.2 项目二:简易网页爬虫

功能需求

  • 获取网页内容
  • 提取所有链接
  • 提取所有图片
  • 保存结果

实现代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import requests
import re
from urllib.parse import urljoin

class SimpleCrawler:
def __init__(self, url):
self.url = url
self.html = self.fetch_page()

def fetch_page(self):
try:
response = requests.get(self.url, timeout=10)
response.raise_for_status()
return response.text
except requests.RequestException as e:
print(f"请求失败: {e}")
return ""

def extract_links(self):
pattern = r'href=["\'](.*?)["\']'
links = re.findall(pattern, self.html)
return [urljoin(self.url, link) for link in links]

def extract_images(self):
pattern = r'src=["\'](.*?\.(?:jpg|jpeg|png|gif))["\']'
images = re.findall(pattern, self.html, re.IGNORECASE)
return [urljoin(self.url, img) for img in images]

def save_results(self, filename="results.txt"):
links = self.extract_links()
images = self.extract_images()

with open(filename, "w") as f:
f.write(f"页面: {self.url}\n\n")
f.write(f"链接 ({len(links)} 个):\n")
for link in links:
f.write(f" {link}\n")
f.write(f"\n图片 ({len(images)} 个):\n")
for img in images:
f.write(f" {img}\n")

print(f"结果已保存到 {filename}")

# 使用示例
# crawler = SimpleCrawler("https://example.com")
# crawler.save_results()

20.3 项目三:数据分析小工具

功能需求

  • 读取 CSV 文件
  • 统计基本信息
  • 计算平均值、最大值、最小值
  • 生成简单报告

实现代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import csv
from collections import defaultdict

class DataAnalyzer:
def __init__(self, filename):
self.filename = filename
self.data = self.load_data()

def load_data(self):
data = []
with open(self.filename, "r", encoding="utf-8") as f:
reader = csv.DictReader(f)
for row in reader:
data.append(row)
return data

def get_column(self, column_name):
return [row[column_name] for row in self.data if column_name in row]

def numeric_stats(self, column_name):
values = [float(x) for x in self.get_column(column_name) if x]
if not values:
return None
return {
"count": len(values),
"sum": sum(values),
"mean": sum(values) / len(values),
"max": max(values),
"min": min(values)
}

def category_count(self, column_name):
values = self.get_column(column_name)
counter = defaultdict(int)
for v in values:
counter[v] += 1
return dict(counter)

def generate_report(self):
print(f"数据文件: {self.filename}")
print(f"总记录数: {len(self.data)}\n")

if self.data:
print("列名:", ", ".join(self.data[0].keys()))
print()

for column in self.data[0].keys():
stats = self.numeric_stats(column)
if stats:
print(f"{column} 统计:")
print(f" 数量: {stats['count']}")
print(f" 总和: {stats['sum']:.2f}")
print(f" 平均: {stats['mean']:.2f}")
print(f" 最大: {stats['max']:.2f}")
print(f" 最小: {stats['min']:.2f}")
else:
counts = self.category_count(column)
print(f"{column} 分类:")
for k, v in counts.items():
print(f" {k}: {v}")
print()

# 使用示例
# analyzer = DataAnalyzer("students.csv")
# analyzer.generate_report()

20.4 项目四:日志分析器

功能需求

  • 读取日志文件
  • 统计错误数量
  • 按级别分类
  • 提取时间范围

实现代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import re
from collections import Counter
from datetime import datetime

class LogAnalyzer:
def __init__(self, filename):
self.filename = filename
self.logs = self.load_logs()

def load_logs(self):
logs = []
pattern = r"(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}) \[(\w+)\] (.+)"

with open(self.filename, "r") as f:
for line in f:
match = re.match(pattern, line.strip())
if match:
logs.append({
"time": match.group(1),
"level": match.group(2),
"message": match.group(3)
})
return logs

def count_by_level(self):
counter = Counter(log["level"] for log in self.logs)
return dict(counter)

def get_errors(self):
return [log for log in self.logs if log["level"] == "ERROR"]

def get_time_range(self):
if not self.logs:
return None, None
times = [log["time"] for log in self.logs]
return times[0], times[-1]

def generate_report(self):
print(f"日志文件: {self.filename}")
print(f"总日志数: {len(self.logs)}\n")

start, end = self.get_time_range()
print(f"时间范围: {start}{end}\n")

counts = self.count_by_level()
print("日志级别统计:")
for level, count in sorted(counts.items()):
print(f" {level}: {count}")

errors = self.get_errors()
if errors:
print(f"\n错误日志 ({len(errors)} 条):")
for error in errors[:5]:
print(f" [{error['time']}] {error['message']}")
if len(errors) > 5:
print(f" ... 还有 {len(errors) - 5} 条错误")

# 使用示例
# analyzer = LogAnalyzer("app.log")
# analyzer.generate_report()

20.5 本章小结

  • 综合运用文件操作、JSON/CSV 处理、正则表达式
  • 面向对象设计提高代码组织性
  • 异常处理保证程序健壮性
  • 模块化设计便于扩展

后续学习建议

  • Web 开发:Flask、Django、FastAPI
  • 数据分析:Pandas、NumPy、Matplotlib
  • 自动化:Requests、Selenium、BeautifulSoup
  • 人工智能:TensorFlow、PyTorch、Scikit-learn
  • 数据库:SQLite、SQLAlchemy、MongoDB

练习题

  1. 扩展通讯录系统,支持模糊搜索
  2. 为爬虫添加深度爬取功能
  3. 为数据分析工具添加导出图表功能
  4. 为日志分析器添加按日期过滤功能
ByteFisher
分享编程技术 · 记录钓鱼乐趣
扫码关注
▸ 扫码关注 ◂
Python基础教程 系列
第 20/20 篇
分享: