本文目录导读:

查看两队历史交锋记录,取决于你手头有什么数据源,以下是几种常见场景的实用脚本方案:
有本地数据库/CSV文件
import pandas as pd
def head_to_head(csv_path, team_a, team_b):
df = pd.read_csv(csv_path) # 需含 home_team, away_team, home_score, away_score, date
mask = (
((df['home_team'] == team_a) & (df['away_team'] == team_b)) |
((df['home_team'] == team_b) & (df['away_team'] == team_a))
)
h2h = df[mask].sort_values('date', ascending=False)
# 统计胜负
a_wins = b_wins = draws = 0
for _, r in h2h.iterrows():
if r['home_score'] == r['away_score']:
draws += 1
else:
winner = r['home_team'] if r['home_score'] > r['away_score'] else r['away_team']
if winner == team_a: a_wins += 1
else: b_wins += 1
print(f"{team_a} vs {team_b}: 共{len(h2h)}场 | {team_a}胜{a_wins} 平{draws} {team_b}胜{b_wins}")
return h2h
h2h = head_to_head("matches.csv", "阿森纳", "切尔西")
print(h2h[['date','home_team','home_score','away_score','away_team']].head(10))
调用公开 API(以 football-data.org 为例)
import requests
API_KEY = "你的key"
HEADERS = {"X-Auth-Token": API_KEY}
def get_h2h(team_a_id, team_b_id, competition="PL"):
url = f"https://api.football-data.org/v4/teams/{team_a_id}/matches"
params = {"competitions": competition, "status": "FINISHED"}
r = requests.get(url, headers=HEADERS, params=params).json()
h2h = []
for m in r.get("matches", []):
home, away = m["homeTeam"]["id"], m["awayTeam"]["id"]
if {home, away} == {team_a_id, team_b_id}:
h2h.append({
"date": m["utcDate"][:10],
"home": m["homeTeam"]["name"],
"score": f'{m["score"]["fullTime"]["home"]}-{m["score"]["fullTime"]["away"]}',
"away": m["awayTeam"]["name"],
})
return h2h
for g in get_h2h(57, 61): # 57=阿森纳, 61=切尔西
print(g)
注意:免费 API 通常有频率限制,且需先通过
/teams接口查 team_id。
爬取网页(示例:某体育数据站)
import requests
from bs4 import BeautifulSoup
def scrape_h2h(url):
headers = {"User-Agent": "Mozilla/5.0"}
soup = BeautifulSoup(requests.get(url, headers=headers).text, "html.parser")
rows = []
for tr in soup.select("table.h2h tbody tr"):
tds = [td.get_text(strip=True) for td in tr.find_all("td")]
if len(tds) >= 4:
rows.append({"date": tds[0], "home": tds[1], "score": tds[2], "away": tds[3]})
return rows
⚠️ 爬虫前请确认目标站点 robots.txt 与服务条款,控制频率,避免封 IP。
命令行快速统计(用 csvkit/jq)
# 假设 matches.csv 有 home_team,away_team,home_score,away_score
csvsql --query "
SELECT COUNT(*) AS 场次,
SUM(CASE WHEN (home_team='阿森纳' AND home_score>away_score)
OR (away_team='阿森纳' AND away_score>home_score) THEN 1 ELSE 0 END) AS 阿森纳胜,
SUM(CASE WHEN home_score=away_score THEN 1 ELSE 0 END) AS 平局
FROM matches
WHERE (home_team='阿森纳' AND away_team='切尔西')
OR (home_team='切尔西' AND away_team='阿森纳')
" matches.csv
关键提醒
- 数据字段要统一:队名拼写("Man Utd" vs "Manchester United")需先做映射归一。
- 主客场处理:统计胜负时要把主队/客队胜负正确归属到队名,不能直接看 home_score。
- 时间过滤:可加
df[df['date'] >= '2020-01-01']只看近期交锋。 - API key 管理:用环境变量而非硬编码。
你具体是在哪个平台/数据源上想查(本地 Excel、某网站、还是某 API)?说清楚我可以给你更贴合的脚本。
版权声明:本站文章为原创整理,转载请注明出处。