实用脚本统计任意球直接得分几次?

wen 实用脚本 4

足球任意球直接得分统计脚本

下面给你一个可直接运行的 Python 实用脚本,用来统计任意球直接得分(直接任意球破门)的次数和详细记录。

实用脚本统计任意球直接得分几次?

基础版(命令行输入记录)

# free_kick_stats.py
import json
import os
DATA_FILE = "free_kick_data.json"
def load_data():
    if os.path.exists(DATA_FILE):
        with open(DATA_FILE, "r", encoding="utf-8") as f:
            return json.load(f)
    return []
def save_data(data):
    with open(DATA_FILE, "w", encoding="utf-8") as f:
        json.dump(data, f, ensure_ascii=False, indent=2)
def add_record():
    """添加一次任意球记录"""
    print("\n--- 新增任意球记录 ---")
    player = input("球员姓名: ").strip()
    team = input("所属球队: ").strip()
    match = input("比赛(如 皇马 vs 巴萨): ").strip()
    minute = input("发生分钟: ").strip()
    result = input("结果(得分/未得分/中框/被扑): ").strip()
    is_goal = result in ("得分", "进球", "goal")
    data = load_data()
    data.append({
        "player": player,
        "team": team,
        "match": match,
        "minute": minute,
        "result": result,
        "is_goal": is_goal,
    })
    save_data(data)
    print(f"✅ 已记录:{player} - {result}")
def show_stats():
    """统计任意球直接得分"""
    data = load_data()
    if not data:
        print("暂无数据。")
        return
    total = len(data)
    goals = [r for r in data if r["is_goal"]]
    goal_count = len(goals)
    rate = goal_count / total * 100 if total else 0
    print("\n========== 任意球统计 ==========")
    print(f"总任意球次数: {total}")
    print(f"直接得分次数: {goal_count}")
    print(f"直接得分率:   {rate:.1f}%")
    # 按球员统计
    print("\n--- 按球员统计得分 ---")
    stat = {}
    for r in data:
        stat.setdefault(r["player"], {"total": 0, "goal": 0})
        stat[r["player"]]["total"] += 1
        if r["is_goal"]:
            stat[r["player"]]["goal"] += 1
    for player, s in sorted(stat.items(), key=lambda x: -x[1]["goal"]):
        print(f"{player:12s} 得分 {s['goal']} / 主罚 {s['total']}")
    # 得分明细
    print("\n--- 得分明细 ---")
    for r in goals:
        print(f"⚽ {r['minute']}分钟 {r['player']}({r['team']}) - {r['match']}")
def menu():
    while True:
        print("\n===== 任意球统计工具 =====")
        print("1. 添加记录")
        print("2. 查看统计")
        print("3. 退出")
        choice = input("请选择: ").strip()
        if choice == "1":
            add_record()
        elif choice == "2":
            show_stats()
        elif choice == "3":
            break
        else:
            print("无效选项")
if __name__ == "__main__":
    menu()

运行方式:

python free_kick_stats.py

数据会自动保存在 free_kick_data.json,下次运行可继续累加。


批量统计版(读取表格)

如果你已有 Excel/CSV 数据(比如从 StatsBomb、Wyscout 或手工整理),用这个:

# batch_stats.py
import pandas as pd
# 假设 CSV 列:player,team,match,minute,result
# result 取值:得分 / 未得分 / 中框 / 被扑
df = pd.read_csv("free_kicks.csv")
# 过滤出"直接任意球"(如果表里有类型列,先筛 type == '直接任意球')
goals = df[df["result"] == "得分"]
print(f"总任意球:{len(df)} 次")
print(f"直接得分:{len(goals)} 次")
print(f"得分率:  {len(goals)/len(df)*100:.1f}%")
print("\n按球员:")
print(goals.groupby("player").size().sort_values(ascending=False))
print("\n得分明细:")
print(goals[["minute", "player", "team", "match"]].to_string(index=False))

CSV 示例:

player,team,match,minute,result
梅西,迈阿密,迈阿密 vs 纽约,32,得分
C罗,利雅得胜利,利雅得 vs 吉达,67,被扑
德布劳内,曼城,曼城 vs 阿森纳,45,得分

接入真实数据源(进阶)

若想统计真实赛事,可以用 StatsBomb Open Data(免费):

import requests
# 示例:拉取某场比赛事件,筛选任意球直接射门
match_id = 3788741  # 需自行查比赛 ID
url = f"https://raw.githubusercontent.com/statsbomb/open-data/master/data/events/{match_id}.json"
events = requests.get(url).json()
free_kick_goals = [
    e for e in events
    if e["type"]["name"] == "Shot"
    and e.get("shot", {}).get("type", {}).get("name") == "Free Kick"
    and e["shot"].get("outcome", {}).get("name") == "Goal"
]
print(f"直接任意球破门:{len(free_kick_goals)} 次")
for g in free_kick_goals:
    print(f"  {g['minute']}' {g['player']['name']}")

使用建议

场景 推荐方案
随手记录几场比赛 方案一
已有表格数据 方案二
想分析真实职业赛事 方案三 + StatsBomb

需要我帮你改成网页版、加上图表可视化,或者按特定联赛/球员定制吗?

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