python案例统计SofaScore综合评分?

wen python案例 1

本文目录导读:

python案例统计SofaScore综合评分?

  1. 方法1:模拟数据统计(推荐教学用)
  2. 方法2:使用爬虫获取真实数据(需要安装相应库)
  3. 方法3:可视化分析
  4. 运行需要的库:
  5. 主要功能:

我来为您创建一个统计SofaScore综合评分的Python案例,由于SofaScore没有官方API,我将提供两种方法:模拟数据和网页爬取。

方法1:模拟数据统计(推荐教学用)

import pandas as pd
import numpy as np
from datetime import datetime
import random
class SofaScoreAnalyzer:
    def __init__(self):
        self.players_data = []
    def generate_sample_data(self, num_players=20):
        """生成模拟的SofaScore球员数据"""
        positions = ['前锋', '中场', '后卫', '门将']
        teams = ['皇马', '巴萨', '曼城', '利物浦', '拜仁', '巴黎']
        for i in range(num_players):
            player = {
                'player_id': f'P{i+1:03d}',
                'name': f'球员{i+1}',
                'team': random.choice(teams),
                'position': random.choice(positions),
                'age': random.randint(18, 35),
                'rating': round(random.uniform(6.0, 9.5), 1),  # SofaScore评分范围6.0-10.0
                'goals': random.randint(0, 20),
                'assists': random.randint(0, 15),
                'minutes_played': random.randint(300, 3000),
                'matches_played': random.randint(10, 38),
                'yellow_cards': random.randint(0, 8),
                'red_cards': random.randint(0, 2)
            }
            self.players_data.append(player)
        return pd.DataFrame(self.players_data)
    def analyze_ratings(self, df):
        """统计分析评分"""
        print("=" * 60)
        print("📊 SofaScore综合评分统计分析")
        print("=" * 60)
        # 1. 总体统计
        print("\n【总体评分统计】")
        print(f"平均评分: {df['rating'].mean():.2f}")
        print(f"最高评分: {df['rating'].max():.2f}")
        print(f"最低评分: {df['rating'].min():.2f}")
        print(f"中位数: {df['rating'].median():.2f}")
        print(f"标准差: {df['rating'].std():.2f}")
        # 2. 按位置分析
        print("\n【按位置评分统计】")
        position_stats = df.groupby('position')['rating'].agg(['mean', 'max', 'min', 'count'])
        print(position_stats.to_string())
        # 3. 按球队分析
        print("\n【按球队评分统计】")
        team_stats = df.groupby('team')['rating'].agg(['mean', 'max', 'min', 'count'])
        team_stats = team_stats.sort_values('mean', ascending=False)
        print(team_stats.to_string())
        # 4. 评分分布
        print("\n【评分分布】")
        rating_bins = pd.cut(df['rating'], bins=[6.0, 7.0, 7.5, 8.0, 8.5, 9.0, 10.0], 
                            labels=['6.0-7.0', '7.0-7.5', '7.5-8.0', '8.0-8.5', '8.5-9.0', '9.0+'])
        distribution = df['rating'].groupby(rating_bins, observed=False).count()
        for interval, count in distribution.items():
            bar = '█' * count
            print(f"{interval}: {count}人 {bar}")
    def find_top_players(self, df, top_n=5):
        """找出评分最高的球员"""
        print("\n" + "=" * 60)
        print(f"🏆 评分最高的{top_n}名球员")
        print("=" * 60)
        top_players = df.nlargest(top_n, 'rating')[['name', 'team', 'position', 'rating', 'goals', 'assists']]
        for idx, player in top_players.iterrows():
            print(f"⭐ {player['name']} ({player['team']}-{player['position']})")
            print(f"   评分: {player['rating']} | 进球: {player['goals']} | 助攻: {player['assists']}")
    def performance_metrics(self, df):
        """计算综合表现指标"""
        print("\n" + "=" * 60)
        print("📈 综合表现指数")
        print("=" * 60)
        # 综合评分(评分权重70% + 进攻贡献20% + 纪律10%)
        df['attack_score'] = (df['goals'] * 2 + df['assists'] * 1.5) / 50
        df['discipline_score'] = 10 - (df['yellow_cards'] * 0.5 + df['red_cards'] * 2)
        df['overall_index'] = df['rating'] * 0.6 + df['attack_score'] * 30 + df['discipline_score'] * 0.4
        # 标准化到0-100
        df['overall_index'] = np.clip(df['overall_index'], 0, 100)
        print("\n评分TOP10球员的综合指数:")
        top_overall = df.nlargest(10, 'overall_index')[['name', 'team', 'rating', 'goals', 'assists', 'overall_index']]
        print(top_overall.to_string(index=False))
        return df
# 使用示例
if __name__ == "__main__":
    # 创建分析器实例
    analyzer = SofaScoreAnalyzer()
    # 生成模拟数据
    df = analyzer.generate_sample_data(num_players=30)
    # 执行分析
    analyzer.analyze_ratings(df)
    analyzer.find_top_players(df, top_n=5)
    df_analyzed = analyzer.performance_metrics(df)
    # 导出数据
    df_analyzed.to_csv('sofascore_ratings.csv', index=False, encoding='utf-8-sig')
    print("\n✅ 数据已保存到 sofascore_ratings.csv")

方法2:使用爬虫获取真实数据(需要安装相应库)

import requests
from bs4 import BeautifulSoup
import pandas as pd
import time
class SofaScoreScraper:
    """SofaScore网页数据爬虫示例"""
    HEADERS = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
    }
    def fetch_player_ratings(self, league_url):
        """获取联赛球员评分数据"""
        try:
            response = requests.get(league_url, headers=self.HEADERS)
            response.raise_for_status()
            soup = BeautifulSoup(response.text, 'html.parser')
            players = []
            # 这里假设页面结构包含球员评分信息
            # 实际SofaScore的页面结构需要根据实际HTML调整
            rating_elements = soup.select('.player-rating')
            name_elements = soup.select('.player-name')
            for name, rating in zip(name_elements, rating_elements):
                player_data = {
                    'name': name.text.strip(),
                    'rating': float(rating.text.strip())
                }
                players.append(player_data)
            return pd.DataFrame(players)
        except Exception as e:
            print(f"抓取失败: {e}")
            return pd.DataFrame()
    def analyze_token_market(self, data_file='sofascore_data.csv'):
        """分析已下载的数据文件"""
        if os.path.exists(data_file):
            df = pd.read_csv(data_file)
            return df.describe()
        return None

方法3:可视化分析

import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
class SofaScoreVisualizer:
    """SofaScore数据可视化"""
    def __init__(self, df):
        self.df = df
    def plot_rating_distribution(self):
        """绘制评分分布图"""
        plt.figure(figsize=(10, 6))
        plt.subplot(1, 2, 1)
        sns.histplot(self.df['rating'], bins=20, kde=True, color='skyblue')
        plt.title('球员评分分布')
        plt.xlabel('SofaScore评分')
        plt.ylabel('球员数量')
        plt.subplot(1, 2, 2)
        sns.boxplot(x='position', y='rating', data=self.df)
        plt.title('不同位置评分对比')
        plt.xticks(rotation=45)
        plt.tight_layout()
        plt.savefig('rating_analysis.png', dpi=300)
        plt.show()
    def plot_team_comparison(self):
        """绘制球队评分对比"""
        plt.figure(figsize=(10, 6))
        team_stats = self.df.groupby('team')['rating'].mean().sort_values(ascending=True)
        plt.barh(range(len(team_stats)), team_stats.values)
        plt.yticks(range(len(team_stats)), team_stats.index)
        plt.xlabel('平均评分')
        plt.title('各球队球员平均评分比较')
        for i, v in enumerate(team_stats.values):
            plt.text(v + 0.02, i, f'{v:.2f}', va='center')
        plt.tight_layout()
        plt.savefig('team_comparison.png', dpi=300)
        plt.show()
# 综合使用示例
def main():
    # 创建分析器
    analyzer = SofaScoreAnalyzer()
    # 生成数据
    df = analyzer.generate_sample_data(num_players=50)
    # 统计分析
    analyzer.analyze_ratings(df)
    analyzer.find_top_players(df)
    df_analyzed = analyzer.performance_metrics(df)
    # 可视化
    visualizer = SofaScoreVisualizer(df_analyzed)
    visualizer.plot_rating_distribution()
    visualizer.plot_team_comparison()
    # 保存结果
    df_analyzed.to_csv('sofascore_full_analysis.csv', index=False)
    print("分析完成!")
if __name__ == "__main__":
    main()

运行需要的库:

pip install pandas numpy matplotlib seaborn beautifulsoup4 requests

主要功能:

  1. 数据分析:均值、中位数、标准差等统计指标
  2. 分组统计:按位置、球队分析
  3. 排名功能:找出评分最高的球员
  4. 综合指标:结合进球、助攻、纪律的综合评分
  5. 可视化:评分分布图、球队对比图

这个案例可以用于足球数据分析和球员评估,您可以根据实际需求调整评分权重和分析维度。

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