Python 分析一场比赛的进球总数
你想用 Python 来获取和统计一场比赛的进球总数,具体方法取决于你的数据来源,我分几种常见场景给你讲:

你已经有比赛数据(最基础)
假设数据是 JSON 或字典格式:
match = {
"home_team": "曼城",
"away_team": "阿森纳",
"home_score": 3,
"away_score": 1
}
total_goals = match["home_score"] + match["away_score"]
print(f"{match['home_team']} vs {match['away_team']} 总进球: {total_goals}")
# 输出:总进球: 4
如果是事件列表(每个进球一条记录):
events = [
{"minute": 12, "type": "goal", "team": "曼城"},
{"minute": 34, "type": "goal", "team": "阿森纳"},
{"minute": 56, "type": "goal", "team": "曼城"},
{"minute": 78, "type": "goal", "team": "曼城"},
{"minute": 85, "type": "yellow_card", "team": "阿森纳"},
]
total_goals = sum(1 for e in events if e["type"] == "goal")
print("总进球:", total_goals) # 4
用 pandas 分析多场比赛
import pandas as pd
df = pd.DataFrame({
"home": ["曼城", "利物浦", "切尔西"],
"away": ["阿森纳", "曼联", "热刺"],
"home_score": [3, 2, 1],
"away_score": [1, 1, 1],
})
df["total_goals"] = df["home_score"] + df["away_score"]
print(df[["home", "away", "total_goals"]])
实时/历史数据 API
常用的足球数据 API:API-Football、Football-Data.org、SportMonks 等。
以 football-data.org 为例:
import requests
API_KEY = "你的API密钥"
url = "https://api.football-data.org/v4/matches/123456" # 比赛ID
headers = {"X-Auth-Token": API_KEY}
resp = requests.get(url, headers=headers).json()
home = resp["score"]["fullTime"]["home"]
away = resp["score"]["fullTime"]["away"]
print(f"总进球: {home + away}")
⚠️ 注意:
- 需要注册拿 API Key(有免费额度)
- 部分接口有速率限制
- 比赛未结束时用
fullTime可能为None,改用halfTime或实时事件
从网页抓取(如懂球帝、SofaScore)
import requests
from bs4 import BeautifulSoup
url = "https://www.sofascore.com/xxx" # 具体比赛页
html = requests.get(url, headers={"User-Agent": "Mozilla/5.0"}).text
soup = BeautifulSoup(html, "html.parser")
# 需要按实际页面结构定位元素
home_score = int(soup.select_one(".home-score").text)
away_score = int(soup.select_one(".away-score").text)
print("总进球:", home_score + away_score)
⚠️ 很多体育网站是 JS 动态渲染的,requests 抓不到,需要用 Selenium / Playwright。
本地数据文件(CSV / Excel)
import pandas as pd
df = pd.read_csv("matches.csv")
match = df[df["match_id"] == 1001].iloc[0]
total = match["home_score"] + match["away_score"]
print(total)
如果你能告诉我:
- 数据从哪来?(API / 网页 / 本地文件 / 自己输入)
- 是单场还是批量?
- 是实时还是赛后?
我可以给你一段直接能跑的完整代码,你也可以把具体的比赛链接或数据样例发我,我帮你写解析逻辑。