python案例统计SofaScore综合评分?

wen python案例 2

Python 统计 SofaScore 综合评分案例

下面我提供几种不同场景下的实现方案,从数据分析到爬虫获取,你可以根据实际需求选择。

python案例统计SofaScore综合评分?


已有评分数据,做统计分析

假设你有一批球员/球队的 SofaScore 评分数据(CSV 格式):

player,team,position,rating,matches,goals,assists
梅西,迈阿密国际,FW,8.42,20,18,12
C罗,利雅得胜利,FW,7.85,22,20,8
姆巴佩,皇马,FW,7.92,21,19,6
贝林厄姆,皇马,MF,7.68,20,12,7
哈兰德,曼城,FW,7.55,22,21,4
德布劳内,曼城,MF,8.10,15,3,14

代码实现

import pandas as pd
import matplotlib.pyplot as plt
import matplotlib
matplotlib.rcParams['font.sans-serif'] = ['SimHei']  # 中文显示
matplotlib.rcParams['axes.unicode_minus'] = False
# 1. 读取数据
df = pd.read_csv('sofascore_ratings.csv')
# 2. 基础统计
print("=" * 50)
print("【综合评分统计】")
print("=" * 50)
print(f"平均评分:   {df['rating'].mean():.2f}")
print(f"最高评分:   {df['rating'].max():.2f}  ({df.loc[df['rating'].idxmax(), 'player']})")
print(f"最低评分:   {df['rating'].min():.2f}  ({df.loc[df['rating'].idxmin(), 'player']})")
print(f"评分中位数: {df['rating'].median():.2f}")
print(f"评分标准差: {df['rating'].std():.2f}")
# 3. 按位置分组统计
print("\n【按位置分组】")
grouped = df.groupby('position')['rating'].agg(['mean', 'max', 'count'])
grouped.columns = ['平均分', '最高分', '人数']
grouped = grouped.round(2).sort_values('平均分', ascending=False)
print(grouped)
# 4. 自定义综合评分(加权计算)
# 评分 70% + 进球效率 20% + 助攻效率 10%
df['综合评分'] = (
    df['rating'] * 0.7 +
    (df['goals'] / df['matches']) * 2 * 0.2 +
    (df['assists'] / df['matches']) * 2 * 0.1
).round(2)
print("\n【自定义综合评分排名】")
rank = df[['player', 'team', 'rating', '综合评分']].sort_values('综合评分', ascending=False)
print(rank.to_string(index=False))
# 5. 可视化
fig, axes = plt.subplots(1, 2, figsize=(14, 5))
# 柱状图:球员评分
axes[0].barh(df['player'], df['rating'], color='#1e88e5')
axes[0].set_xlabel('SofaScore 评分')
axes[0].set_title('球员 SofaScore 评分对比')
axes[0].invert_yaxis()
for i, v in enumerate(df['rating']):
    axes[0].text(v + 0.02, i, f'{v:.2f}', va='center')
# 散点图:评分 vs 场均进球
axes[1].scatter(df['rating'], df['goals'] / df['matches'], s=100, c='#e53935')
for _, row in df.iterrows():
    axes[1].annotate(row['player'], (row['rating'], row['goals']/row['matches']),
                     xytext=(5, 5), textcoords='offset points')
axes[1].set_xlabel('SofaScore 评分')
axes[1].set_ylabel('场均进球')
axes[1].set_title('评分 vs 场均进球')
plt.tight_layout()
plt.savefig('sofascore_analysis.png', dpi=100)
plt.show()

输出示例

==================================================
【综合评分统计】
==================================================
平均评分:   7.92
最高评分:   8.42  (梅西)
最低评分:   7.55  (哈兰德)
评分中位数: 7.85
评分标准差: 0.30
【按位置分组】
          平均分  最高分  人数
position
MF        7.89  8.10    2
FW        7.94  8.42    4
【自定义综合评分排名】
    player       team  rating  综合评分
      梅西  迈阿密国际    8.42   7.11
      姆巴佩      皇马    7.92   7.02
    贝林厄姆      皇马    7.68   6.90
       C罗  利雅得胜利    7.85   6.83
   德布劳内      曼城    8.10   6.74
     哈兰德      曼城    7.55   6.71

模拟调用 SofaScore API 获取评分

SofaScore 有非官方的 API(仅供学习研究,注意遵守使用条款):

import requests
import pandas as pd
import time
def get_team_ratings(team_id, tournament_id=17, season_id=52186):
    """
    获取球队在特定赛事中的球员评分
    team_id: 球队ID
    tournament_id: 赛事ID (17=英超, 8=西甲, 35=德甲 等)
    season_id: 赛季ID
    """
    url = f"https://api.sofascore.com/api/v1/team/{team_id}/unique-tournament/{tournament_id}/season/{season_id}/top-players/overall"
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
    }
    try:
        resp = requests.get(url, headers=headers, timeout=10)
        resp.raise_for_status()
        data = resp.json()
        players = []
        for item in data.get("topPlayers", {}).get("rating", []):
            p = item["player"]
            players.append({
                "player": p["name"],
                "player_id": p["id"],
                "rating": round(item["statistics"]["rating"], 2),
                "appearances": item["statistics"].get("appearances", 0),
                "goals": item["statistics"].get("goals", 0),
                "assists": item["statistics"].get("assists", 0),
            })
        return pd.DataFrame(players)
    except Exception as e:
        print(f"请求失败: {e}")
        return pd.DataFrame()
# 使用示例(曼联 team_id = 35)
df = get_team_ratings(team_id=35, tournament_id=17)
if not df.empty:
    df = df.sort_values('rating', ascending=False)
    print("【球队球员评分 TOP 10】")
    print(df.head(10).to_string(index=False))
    # 加权综合评分
    df['综合分'] = (
        df['rating'] * 0.7 +
        (df['goals'] / df['appearances'].replace(0, 1)) * 2 +
        (df['assists'] / df['appearances'].replace(0, 1)) * 1
    ).round(2)
    print("\n【综合评分排名】")
    print(df.sort_values('综合分', ascending=False).head(10).to_string(index=False))
time.sleep(1)  # 礼貌性延时

批量抓取多赛季评分并出趋势图

import requests
import pandas as pd
import matplotlib.pyplot as plt
def fetch_player_season_rating(player_id, season_ids):
    """抓取一名球员多个赛季的评分"""
    headers = {"User-Agent": "Mozilla/5.0"}
    records = []
    for season in season_ids:
        url = f"https://api.sofascore.com/api/v1/player/{player_id}/unique-tournament/17/season/{season}/statistics/overall"
        try:
            r = requests.get(url, headers=headers, timeout=10)
            data = r.json().get("statistics", {})
            records.append({
                "season": season,
                "rating": data.get("rating", 0),
                "appearances": data.get("appearances", 0),
                "goals": data.get("goals", 0),
                "assists": data.get("assists", 0),
            })
        except Exception as e:
            print(f"{season}: 失败 {e}")
        time.sleep(0.5)
    return pd.DataFrame(records)
seasons = [52186, 61627, 70256, 86668]  # 赛季ID示例
df = fetch_player_season_rating(player_id=1234, season_ids=seasons)
if not df.empty:
    fig, ax1 = plt.subplots(figsize=(10, 5))
    ax1.plot(df['season'].astype(str), df['rating'], 'o-', color='#1e88e5', label='评分')
    ax1.set_ylabel('SofaScore 评分', color='#1e88e5')
    ax1.set_xlabel('赛季')
    ax2 = ax1.twinx()
    ax2.bar(df['season'].astype(str), df['goals'], alpha=0.3, color='#e53935', label='进球')
    ax2.set_ylabel('进球数', color='#e53935')
    plt.title('球员 SofaScore 评分与进球趋势')
    plt.tight_layout()
    plt.show()

关键要点说明

环节 建议
数据源 优先使用公开数据集或官方 API;爬虫注意频率限制(time.sleep)
综合评分 不要直接用原始 rating 排序,建议加权(rating + 关键数据)
评分归一化 不同赛事评分尺度不同,需做 z-score 或 min-max 归一化
位置差异 前锋/中场/后卫评分标准不同,建议分位置统计
可视化 matplotlib/seaborn/plotly 都能用,注意中文字体设置

需要我进一步帮你吗?

可以告诉我:

  1. 你是想要爬取真实数据 还是 分析已有数据?
  2. 数据来源是 CSV / Excel / API / 网页?
  3. 想统计球员还是球队?单赛季还是多赛季对比?

我可以针对你的具体场景给出完整可运行代码。

抱歉,评论功能暂时关闭!