前面六章是“零件”,这一章把它们组装成能用的工具。我们用三个真实项目,把语法、数据处理、自动化、面向对象全部串起来——你会发现,所谓“做项目”,不过是把已知的能力按需求组合。
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("scores.csv")
subjects = ["数学", "英语", "语文"]
# 1) 统计
print(df[subjects].mean().round(1)) # 各科平均分
print("最高总分:", df[subjects].sum(axis=1).max())
# 2) 画柱状图
df[subjects].mean().plot(kind="bar", color=["#b04a2c", "#5e7a46", "#b06a24"])
plt.title("各科平均分")
plt.savefig("avg.png") # 保存图片
print("报告图已生成:avg.png")
import csv, io, statistics
csv_text = """姓名,数学,英语,语文
小明,90,85,88
小红,82,79,91
小刚,80,86,85
"""
def build_report(text, subjects, ndigits=1):
rows = list(csv.DictReader(io.StringIO(text)))
print("分析科目:", subjects)
for s in subjects:
scores = [int(r[s]) for r in rows]
print(f" {s} 平均分:{round(statistics.mean(scores), ndigits)}")
best = max(rows, key=lambda r: sum(int(r[s]) for s in subjects))
print("总分最高:", best["姓名"])
# 改这里就能换分析的科目 / 小数位数
build_report(csv_text, ["数学", "英语", "语文"], ndigits=1)
import os, shutil, re, datetime
def organize(folder):
for name in os.listdir(folder):
src = os.path.join(folder, name)
if not os.path.isfile(src):
continue
try:
m = re.search(r"(\d{4})-(\d{2})", name)
ym = m.group(1) + "-" + m.group(2) if m else \
datetime.datetime.fromtimestamp(os.path.getmtime(src)).strftime("%Y-%m")
dest = os.path.join(folder, ym)
os.makedirs(dest, exist_ok=True)
shutil.move(src, os.path.join(dest, name))
print("已整理", name, "→", ym)
except Exception as e: # 单个文件出错不影响整体
print("跳过", name, "原因:", e)
if __name__ == "__main__":
organize("downloads")
import os, shutil, re, tempfile
def organize(folder, dry_run=True):
for name in sorted(os.listdir(folder)):
src = os.path.join(folder, name)
if not os.path.isfile(src):
continue
m = re.search(r"(\d{4})-(\d{2})", name)
ym = m.group(1) + "-" + m.group(2) if m else "未知月份"
dest = os.path.join(folder, ym)
if dry_run:
print("将移动(预览):", name, "→", ym)
else:
os.makedirs(dest, exist_ok=True)
shutil.move(src, os.path.join(dest, name))
print("已移动:", name, "→", ym)
# 建一个临时测试目录
tmp = tempfile.mkdtemp()
for f in ["报告-2026-09.pdf", "照片-2026-08.jpg", "笔记.txt"]:
open(os.path.join(tmp, f), "w").close()
print("=== 预览模式(dry_run=True,不动文件)===")
organize(tmp, dry_run=True)
import requests, re
def fetch_links(url):
try:
r = requests.get(url, timeout=5)
r.raise_for_status() # 非 200 直接抛异常
html = r.text
title = re.search(r"(.*?) ", html, re.S)
links = re.findall(r'href="(.*?)"', html)
return (title.group(1).strip() if title else "无标题", links)
except Exception as e:
return ("抓取失败", [str(e)])
t, links = fetch_links("https://example.com")
print("标题:", t)
print("前 5 个链接:", links[:5])
import re
html = '''
<html><head><title>示例学院官网</title></head>
<body>
<a href="https://a.edu/index">首页</a>
<a href="/news/1">新闻</a>
<img src="logo.png">
</body></html>
'''
title = re.search(r"<title>(.*?)</title>", html, re.S)
links = re.findall(r'href="(.*?)"', html)
print("标题:", title.group(1).strip() if title else "无标题")
print("提取到的链接:")
for i, u in enumerate(links, 1):
print(f" {i}. {u}")
1给 build_report 增加“及格率”统计:输出每科分数 ≥60 的比例(百分比整数)。
提示:用列表推导收集每科分数,再数出 ≥60 的个数除以总人数。
import csv, io
csv_text = """姓名,数学,英语,语文
小明,90,85,88
小红,82,79,91
小刚,80,86,85
小绿,55,40,62
"""
rows = list(csv.DictReader(io.StringIO(csv_text)))
for s in ["数学","英语","语文"]:
scores=[int(r[s]) for r in rows]
pass_rate=sum(1 for x in scores if x>=60)/len(scores)
print(f"{s} 及格率:{pass_rate*100:.0f}%")
2把整理工具改成“按扩展名分类”:把 .pdf 放进 pdf_files、.jpg 放进 jpg_files。
提示:用 name.rsplit(".",1) 取扩展名,再 os.makedirs(..., exist_ok=True) 建子目录。
import os, shutil, tempfile
def organize_by_ext(folder):
for name in sorted(os.listdir(folder)):
src=os.path.join(folder,name)
if not os.path.isfile(src): continue
ext=name.rsplit(".",1)[-1].lower() if "." in name else "无扩展名"
dest=os.path.join(folder,ext+"_files")
os.makedirs(dest,exist_ok=True)
shutil.move(src,os.path.join(dest,name))
print("已归类",name,"→",ext+"_files")
tmp=tempfile.mkdtemp()
for f in ["a.pdf","b.jpg","c.pdf","d.txt"]:
open(os.path.join(tmp,f),"w").close()
organize_by_ext(tmp)
for d in sorted(os.listdir(tmp)):
print(d, ":", sorted(os.listdir(os.path.join(tmp,d))))
3仿照提取链接,用正则提取页面里所有图片的 src 地址。
提示:匹配 <img ... src="..."> 模式,注意 . 不要跨过 "。
import re
html='''<img src="logo.png"><img src="https://cdn.x.com/b.png">
<a href="page.html">链接</a>'''
imgs=re.findall(r'<img[^>]*src="(.*?)"',html)
print("图片地址共",len(imgs),"个:")
for u in imgs: print(" -",u)