本文目录导读:

- 方法一:使用
pandas处理CSV数据(最常用) - 方法二:计算直接交锋数据
- 方法三:使用Web API(实时数据)
- 方法四:数据可视化
- 方法五:使用
requests-html爬取网站数据 - 使用示例整合
- 完整解决方案示例
我来给你介绍几种查看两队历史交锋记录的Python方法,从简单到复杂都有。
使用pandas处理CSV数据(最常用)
import pandas as pd
# 假设你有一个包含历史比赛数据的CSV文件
# 格式:日期,主队,客队,主队进球,客队进球
def load_match_history(csv_path='matches.csv'):
"""加载比赛历史数据"""
df = pd.read_csv(csv_path)
return df
def get_head_to_head(df, team1, team2):
"""查询两队的历史交锋记录"""
# 方法1:筛选两队相遇的比赛(不管主客场)
matches = df[
((df['主队'] == team1) & (df['客队'] == team2)) |
((df['主队'] == team2) & (df['客队'] == team1))
].sort_values('日期')
return matches
# 使用示例
df = load_match_history()
h2h = get_head_to_head(df, '皇马', '巴萨')
print(f"两队交锋次数: {len(h2h)}")
print(h2h)
计算直接交锋数据
def get_head_to_head_stats(df, team1, team2):
"""计算两队交锋的详细统计"""
# 获取交锋记录
matches = get_head_to_head(df, team1, team2)
# 统计结果
stats = {
'total_matches': len(matches),
'team1_wins': 0,
'team2_wins': 0,
'draws': 0,
'team1_goals': 0,
'team2_goals': 0,
'recent_matches': []
}
for _, match in matches.iterrows():
home_team = match['主队']
home_goals = match['主队进球']
away_goals = match['客队进球']
# 判断哪支球队是team1
if home_team == team1:
team1_goals = home_goals
team2_goals = away_goals
else:
team1_goals = away_goals
team2_goals = home_goals
# 统计胜负
if team1_goals > team2_goals:
stats['team1_wins'] += 1
elif team1_goals < team2_goals:
stats['team2_wins'] += 1
else:
stats['draws'] += 1
# 累计进球
stats['team1_goals'] += team1_goals
stats['team2_goals'] += team2_goals
# 最近5场比赛
stats['recent_matches'] = matches.tail(5).to_dict('records')
return stats
# 使用
stats = get_head_to_head_stats(df, '皇马', '巴萨')
print(f"总交锋: {stats['total_matches']}次")
print(f"皇马胜: {stats['team1_wins']}次")
print(f"巴萨胜: {stats['team2_wins']}次")
print(f"平局: {stats['draws']}次")
print(f"总进球比: {stats['team1_goals']}:{stats['team2_goals']}")
使用Web API(实时数据)
import requests
import json
def get_h2h_from_api(team1_id, team2_id, api_key=None):
"""
使用足球API获取交锋记录
推荐API:API-Football (需要API密钥)
"""
# API-Football 示例
headers = {
'x-rapidapi-host': "v3.football.api-sports.io",
'x-rapidapi-key': api_key or "YOUR_API_KEY"
}
# 获取两支球队的H2H
url = "https://v3.football.api-sports.io/fixtures/headtohead"
params = {
'h2h': f"{team1_id}-{team2_id}",
'last': 10 # 最近10场
}
response = requests.get(url, headers=headers, params=params)
if response.status_code == 200:
data = response.json()
return data.get('response', [])
else:
return []
数据可视化
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
def visualize_h2h(df, team1, team2, stats):
"""可视化两队交锋数据"""
# 1. 获胜统计饼图
fig, axes = plt.subplots(1, 3, figsize=(15, 5))
# 饼图:胜负分布
labels = [f'{team1} 胜', '平局', f'{team2} 胜']
sizes = [stats['team1_wins'], stats['draws'], stats['team2_wins']]
colors = ['#00FF00', '#FFFF00', '#FF0000']
axes[0].pie(sizes, labels=labels, colors=colors, autopct='%1.1f%%')
axes[0].set_title(f'{team1} vs {team2} 胜率分布')
# 折线图:近期比赛结果走势
matches = get_head_to_head(df, team1, team2)
recent = matches.tail(10)
# 计算净胜球
net_goals = []
for _, match in recent.iterrows():
if match['主队'] == team1:
net = match['主队进球'] - match['客队进球']
else:
net = match['客队进球'] - match['主队进球']
net_goals.append(net)
axes[1].plot(range(len(recent)), net_goals, marker='o')
axes[1].axhline(y=0, color='gray', linestyle='--')
axes[1].set_title(f'len(recent)}场净胜球走势')
axes[1].set_xlabel('比赛场次')
axes[1].set_ylabel(f'{team1} 净胜球')
# 柱状图:总进球对比
axes[2].bar([0, 1], [stats['team1_goals'], stats['team2_goals']])
axes[2].set_xticks([0, 1])
axes[2].set_xticklabels([team1, team2])
axes[2].set_title('历史总进球对比')
axes[2].set_ylabel('进球数')
plt.tight_layout()
plt.show()
使用requests-html爬取网站数据
from bs4 import BeautifulSoup
import requests
def scrape_h2h(url):
"""从网站爬取交锋记录"""
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
}
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.content, 'html.parser')
# 这里需要根据具体网站结构调整选择器
# 以知乎/微博等体育板块为例
matches = []
# 示例:提取比赛结果
for match in soup.select('.match-result-class'):
date = match.find('span', class_='date').text
home_team = match.find('span', class_='home-team').text
away_team = match.find('span', class_='away-team').text
score = match.find('span', class_='score').text
matches.append({
'date': date,
'home_team': home_team,
'away_team': away_team,
'score': score
})
return matches
使用示例整合
from datetime import datetime
import pandas as pd
# 示例数据创建
sample_data = {
'日期': ['2023-01-15', '2023-04-02', '2023-04-15', '2023-05-20'],
'主队': ['皇马', '巴萨', '皇马', '巴萨'],
'客队': ['巴萨', '皇马', '巴萨', '皇马'],
'主队进球': [2, 1, 0, 2],
'客队进球': [1, 0, 3, 2]
}
df = pd.DataFrame(sample_data)
df['日期'] = pd.to_datetime(df['日期'])
# 查看交锋记录
h2h = get_head_to_head(df, '皇马', '巴萨')
print("交锋记录表:")
print(h2h)
# 查看统计
stats = get_head_to_head_stats(df, '皇马', '巴萨')
print("\n交锋统计:")
print(f"总比赛数: {stats['total_matches']}")
print(f"皇马胜: {stats['team1_wins']}场")
print(f"巴萨胜: {stats['team2_wins']}场")
print(f"平局: {stats['draws']}场")
print(f"皇马进球: {stats['team1_goals']}个")
print(f"巴萨进球: {stats['team2_goals']}个")
完整解决方案示例
class HeadToHeadAnalyzer:
"""两队交锋分析器"""
def __init__(self, data_source='csv'):
self.data = None
self.data_source = data_source
def load_data(self, file_path=None):
"""加载数据"""
if self.data_source == 'csv' and file_path:
self.data = pd.read_csv(file_path)
return self
def analyze_h2h(self, team1, team2, visualize=False):
"""分析两队交锋"""
# 计算交锋记录
h2h = get_head_to_head(self.data, team1, team2)
stats = get_head_to_head_stats(self.data, team1, team2)
result = {
'matches': h2h,
'stats': stats,
'analysis': self.generate_analysis(team1, team2, stats)
}
# 可选可视化
if visualize:
visualize_h2h(self.data, team1, team2, stats)
return result
def generate_analysis(self, team1, team2, stats):
"""生成分析报告"""
analysis = f"""
=== {team1} vs {team2} 历史交锋分析 ===
总交锋次数:{stats['total_matches']}场
{team1}胜:{stats['team1_wins']} 场({stats['team1_wins']/stats['total_matches']*100:.1f}%)
平局:{stats['draws']} 场
{team2}胜:{stats['team2_wins']} 场({stats['team2_wins']/stats['total_matches']*100:.1f}%)
进球数据:
{team1}总进球:{stats['team1_goals']}个(场均{stats['team1_goals']/stats['total_matches']:.2f})
{team2}总进球:{stats['team2_goals']}个(场均{stats['team2_goals']/stats['total_matches']:.2f})
"""
if stats['team1_wins'] > stats['team2_wins']:
analysis += f"{team1}在历史交锋中占据优势"
elif stats['team2_wins'] > stats['team1_wins']:
analysis += f"{team2}在历史交锋中占据优势"
else:
analysis += "两队历史交锋势均力敌"
return analysis
# 使用示例
analyzer = HeadToHeadAnalyzer('csv')
analyzer.load_data('team_matches.csv')
result = analyzer.analyze_h2h('皇马', '巴萨', visualize=True)
print(result['analysis'])
这些方法各有特点:
- 方法1-2:适合本地数据分析
- 方法3:需要API密钥,实时数据
- 方法4:数据可视化展示
- 方法5:网络爬虫,注意遵守robots.txt
选择哪种方法取决于你的数据来源和具体需求,最常用的是第一种方法(pandas处理CSV),因为大多数情况下你会有历史比赛数据的CSV文件。