本文目录导读:

我来帮你写一个Python案例,分析球队近期状态,这个案例可以抓取/模拟球队近期比赛数据,计算状态指标。
完整案例:球队近期状态分析
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from datetime import datetime, timedelta
# 设置中文显示
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
class TeamFormAnalyzer:
"""球队近期状态分析器"""
def __init__(self, team_name):
self.team_name = team_name
self.matches = []
def add_match(self, date, opponent, goals_for, goals_against, is_home=True):
"""添加一场比赛记录"""
self.matches.append({
'date': pd.to_datetime(date),
'opponent': opponent,
'goals_for': goals_for,
'goals_against': goals_against,
'is_home': is_home,
'result': 'W' if goals_for > goals_against
else ('D' if goals_for == goals_against else 'L'),
'points': 3 if goals_for > goals_against
else (1 if goals_for == goals_against else 0)
})
def get_recent_form(self, n=5):
"""获取最近n场比赛状态"""
df = pd.DataFrame(self.matches).sort_values('date', ascending=False)
return df.head(n)
def calculate_metrics(self, n=5):
"""计算近期状态指标"""
recent = self.get_recent_form(n)
metrics = {
'比赛场数': len(recent),
'胜/平/负': f"{sum(recent['result']=='W')}/{sum(recent['result']=='D')}/{sum(recent['result']=='L')}",
'积分': recent['points'].sum(),
'场均积分': round(recent['points'].mean(), 2),
'进球数': recent['goals_for'].sum(),
'失球数': recent['goals_against'].sum(),
'净胜球': recent['goals_for'].sum() - recent['goals_against'].sum(),
'场均进球': round(recent['goals_for'].mean(), 2),
'场均失球': round(recent['goals_against'].mean(), 2),
'胜率': f"{sum(recent['result']=='W')/len(recent)*100:.0f}%",
}
return metrics
def form_string(self, n=5):
"""生成状态字符串,如 WWDLW"""
recent = self.get_recent_form(n).sort_values('date')
return ''.join(recent['result'].tolist())
def calculate_momentum(self, n=10):
"""计算势头指数(越近的比赛权重越高)"""
recent = self.get_recent_form(n).sort_values('date')
weights = np.arange(1, len(recent) + 1) # 越新权重越高
weighted_points = np.average(recent['points'], weights=weights)
return round(weighted_points, 2)
def plot_form(self, n=10):
"""可视化近期状态"""
recent = self.get_recent_form(n).sort_values('date')
fig, axes = plt.subplots(1, 2, figsize=(14, 5))
# 图1:积分趋势
axes[0].plot(recent['date'], recent['points'].cumsum(),
marker='o', color='#2E86AB', linewidth=2)
axes[0].set_title(f'{self.team_name} 近{n}场积分走势')
axes[0].set_xlabel('日期')
axes[0].set_ylabel('累计积分')
axes[0].grid(alpha=0.3)
axes[0].tick_params(axis='x', rotation=45)
# 图2:进失球
x = np.arange(len(recent))
width = 0.35
axes[1].bar(x - width/2, recent['goals_for'], width,
label='进球', color='#06A77D')
axes[1].bar(x + width/2, recent['goals_against'], width,
label='失球', color='#D62828')
axes[1].set_xticks(x)
axes[1].set_xticklabels([f"vs {o}" for o in recent['opponent']], rotation=45)
axes[1].set_title(f'{self.team_name} 近{n}场进失球')
axes[1].legend()
axes[1].grid(alpha=0.3, axis='y')
plt.tight_layout()
plt.show()
def generate_report(self, n=5):
"""生成状态报告"""
metrics = self.calculate_metrics(n)
print(f"\n{'='*50}")
print(f" {self.team_name} 近期状态分析(近{n}场)")
print(f"{'='*50}")
for key, value in metrics.items():
print(f" {key:<8}: {value}")
print(f"\n 状态走势: {self.form_string(n)}")
print(f" 势头指数: {self.calculate_momentum(10)} (满分3.0)")
# 状态评价
avg_pts = metrics['场均积分']
if avg_pts >= 2.2:
rating = "🔥 状态火热"
elif avg_pts >= 1.6:
rating = "✅ 状态良好"
elif avg_pts >= 1.0:
rating = "😐 状态一般"
else:
rating = "❄️ 状态低迷"
print(f" 综合评价: {rating}")
print(f"{'='*50}\n")
# ========== 使用示例 ==========
if __name__ == "__main__":
# 创建分析器(示例数据:某支球队)
team = TeamFormAnalyzer("曼城")
# 添加近期比赛(可以从数据源获取)
matches_data = [
('2024-11-01', '阿森纳', 2, 1, True),
('2024-11-05', '切尔西', 3, 0, False),
('2024-11-10', '利物浦', 1, 1, True),
('2024-11-15', '热刺', 2, 2, False),
('2024-11-20', '纽卡斯尔', 4, 1, True),
('2024-11-25', '布莱顿', 1, 0, False),
('2024-11-30', '曼联', 3, 1, True),
('2024-12-05', '维拉', 2, 3, False),
('2024-12-10', '埃弗顿', 2, 0, True),
('2024-12-15', '西汉姆', 1, 1, False),
]
for date, opp, gf, ga, home in matches_data:
team.add_match(date, opp, gf, ga, home)
# 生成报告
team.generate_report(n=5)
team.generate_report(n=10)
# 可视化
team.plot_form(n=10)
输出示例
==================================================
曼城 近期状态分析(近5场)
==================================================
比赛场数 : 5
胜/平/负 : 3/1/1
积分 : 10
场均积分 : 2.0
进球数 : 11
失球数 : 5
净胜球 : 6
场均进球 : 2.2
场均失球 : 1.0
胜率 : 60%
状态走势: LWDWW
势头指数: 2.15 (满分3.0)
综合评价: ✅ 状态良好
==================================================
关键设计点
| 模块 | 作用 |
|---|---|
add_match() |
灵活录入比赛数据 |
get_recent_form(n) |
提取最近n场 |
calculate_metrics() |
综合状态指标 |
form_string() |
WWDLW 直观展示 |
calculate_momentum() |
加权势头(越新越重要) |
plot_form() |
双图可视化 |
数据源扩展建议
如果想接入真实数据:
-
免费API
football-data.org(部分免费)TheSportsDB(免费)OpenLigaDB(免费)
-
爬虫方案
- 使用
requests + BeautifulSoup抓取懂球帝、虎扑 - 使用
Selenium处理动态页面 - 使用
soccerdata库(Python包)
- 使用
-
接入示例
import requests
def fetch_team_matches(team_id, api_key): url = f"https://api.football-data.org/v4/teams/{team_id}/matches" headers = {'X-Auth-Token': api_key} resp = requests.get(url, headers=headers).json() return resp['matches']
需要我扩展哪部分?*接入真实API**、**加入对手实力加权**、**对比多支球队**,或者**做赛程难度预测**?