我来帮你创建一个统计犯规战术阻止反击次数的Python案例,这个程序可以分析比赛数据,识别哪些犯规属于战术犯规(阻止了可能的反击机会)。

import re
from datetime import datetime
from typing import List, Dict, Optional
class FootballMatchAnalyzer:
"""足球比赛战术犯规分析器"""
def __init__(self):
# 比赛事件数据
self.events = []
# 反击判定参数
self.counterattack_distance = 30 # 距离本方球门30米以上视为有反击机会
self.time_window = 3 # 抢断后3秒内通常是最佳反击时间
def add_event(self, minute: int, second: int, team: str, event_type: str,
player: str, position_x: float, position_y: float,
detail: str = ""):
"""添加比赛事件
参数:
minute: 比赛分钟
second: 秒数
team: 球队名称
event_type: 事件类型(tackle/foul/goal等)
player: 球员姓名
position_x, position_y: 位置坐标(球场半场坐标0-100)
detail: 事件详情
"""
event = {
'time': minute * 60 + second,
'team': team,
'type': event_type,
'player': player,
'x': position_x,
'y': position_y,
'detail': detail,
'counterattack': False # 是否属于反击机会
}
self.events.append(event)
def analyze_counterattack_fouls(self) -> Dict:
"""分析战术犯规阻止反击的次数"""
results = {
'total_fouls': 0,
'tactical_fouls': 0,
'counterattack_fouls': 0,
'normal_fouls': 0,
'details': []
}
# 按时间排序事件
sorted_events = sorted(self.events, key=lambda x: x['time'])
for i, event in enumerate(sorted_events):
if event['type'] != 'foul':
continue
results['total_fouls'] += 1
# 检查犯规前的5秒内是否有抢断或传球
previous_events = [e for e in sorted_events[:i]
if e['time'] >= event['time'] - 5
and e['time'] < event['time']]
# 判断是否有反击机会
has_counterattack = False
counterattack_detail = ""
# 条件1: 对方刚抢断球权
for prev_event in previous_events:
if prev_event['type'] in ['tackle', 'interception']:
distance = self._calculate_distance(
prev_event['x'], prev_event['y'],
event['x'], event['y']
)
if distance > self.counterattack_distance:
has_counterattack = True
counterattack_detail = f"抢断后反击距离{distance:.0f}米"
break
# 条件2: 对方在进攻三区准备进攻
if not has_counterattack and event['x'] > 60: # 对方半场
has_counterattack = True
counterattack_detail = f"进攻区域犯规(位置x={event['x']})"
# 条件3: 对方人数占优
if not has_counterattack:
# 简化判断:如果犯规位置在中场且之前有快速推进
speed_check = self._check_movement_speed(previous_events)
if speed_check:
has_counterattack = True
counterattack_detail = "快速推进后阻止反击"
if has_counterattack:
results['counterattack_fouls'] += 1
results['tactical_fouls'] += 1
results['details'].append({
'minute': event['time'] // 60,
'second': event['time'] % 60,
'team': event['team'],
'player': event['player'],
'reason': counterattack_detail
})
else:
results['normal_fouls'] += 1
return results
def _calculate_distance(self, x1: float, y1: float, x2: float, y2: float) -> float:
"""计算两事件之间的距离"""
return ((x1 - x2) ** 2 + (y1 - y2) ** 2) ** 0.5
def _check_movement_speed(self, events: List[Dict]) -> bool:
"""检查是否有快速移动"""
if len(events) < 2:
return False
# 计算最近的两个事件间的移动速度
last_events = events[-2:]
time_diff = last_events[1]['time'] - last_events[0]['time']
if time_diff <= 0:
return False
distance = self._calculate_distance(
last_events[0]['x'], last_events[0]['y'],
last_events[1]['x'], last_events[1]['y']
)
# 每秒移动超过5米视为快速移动
return distance / time_diff > 5
def add_match_data_from_text(self, text: str):
"""从文本数据解析比赛事件"""
# 简化版文本解析示例
lines = text.strip().split('\n')
for line in lines:
# 假设格式: "分钟:秒 队伍 事件类型 球员 X坐标 Y坐标 详情"
parts = line.split()
if len(parts) >= 7:
time_parts = parts[0].split(':')
minute = int(time_parts[0])
second = int(time_parts[1])
team = parts[1]
event_type = parts[2]
player = parts[3]
x = float(parts[4])
y = float(parts[5])
detail = ' '.join(parts[6:]) if len(parts) > 6 else ""
self.add_event(minute, second, team, event_type, player, x, y, detail)
def create_sample_match():
"""创建一个示例比赛数据"""
analyzer = FootballMatchAnalyzer()
# 模拟一场比赛的数据
# 时间格式: 分钟:秒 球队 事件类型 球员 X坐标 Y坐标 详情
match_data = """
5:30 主队 tackle 张三 70 50 中场抢断
5:32 主队 foul 李四 75 45 阻止对方反击
5:35 客队 pass 王五 60 40
12:00 客队 tackle 赵六 80 30 前场抢断
12:03 主队 foul 孙七 65 35 战术犯规阻止反击
12:05 客队 foul 周八 90 45 防守犯规
25:30 主队 pass 张三 50 50
25:35 客队 tackle 王五 65 55 中场抢断
25:37 主队 foul 李四 60 50 快速推进中犯规
25:40 客队 shot 赵六 80 50
40:00 客队 interception 钱九 70 60 拦截传球
40:02 主队 foul 孙七 75 45 破坏反击机会
40:05 客队 foul 周八 50 50 普通防守犯规
55:00 主队 pass 张三 40 60
55:02 客队 foul 王五 35 55 前场压迫犯规
55:10 主队 shot 李四 80 50
60:30 客队 tackle 赵六 85 35 后场抢断
60:33 主队 foul 孙七 78 40 阻止对方快速反击
60:36 客队 pass 钱九 68 45
75:00 主队 interception 张三 55 45 中场拦截
75:03 客队 foul 王五 60 40 战术犯规
75:06 主队 shot 李四 75 50
85:30 客队 tackle 赵六 90 20 后场解围式抢断
85:31 主队 foul 孙七 65 35 快速反击中的犯规
85:34 客队 pass 钱九 70 45
"""
analyzer.add_match_data_from_text(match_data)
return analyzer
def main():
"""主函数"""
print("=" * 60)
print("足球比赛战术犯规阻止反击分析系统")
print("=" * 60)
# 创建并分析比赛
analyzer = create_sample_match()
# 执行分析
results = analyzer.analyze_counterattack_fouls()
# 输出分析结果
print(f"\n📊 比赛犯规统计结果:")
print(f"{'='*60}")
print(f"总犯规次数:{results['total_fouls']} 次")
print(f"战术犯规次数:{results['tactical_fouls']} 次")
print(f"其中阻止反击的犯规:{results['counterattack_fouls']} 次")
print(f"普通犯规:{results['normal_fouls']} 次")
print(f"\n🎯 战术犯规阻止反击明细:")
print(f"{'='*60}")
if results['details']:
for detail in results['details']:
print(f"时间: {detail['minute']}:{detail['second']:02d} | "
f"球队: {detail['team']} | "
f"球员: {detail['player']} | "
f"原因: {detail['reason']}")
else:
print("没有检测到战术犯规阻止反击的情况")
# 计算比率
if results['total_fouls'] > 0:
ratio = (results['counterattack_fouls'] / results['total_fouls']) * 100
print(f"\n📈 战术犯规占比:{ratio:.1f}%")
# 附加分析
print(f"\n📋 额外分析:")
print(f"{'='*60}")
# 按球队分组统计
team_stats = {}
for event in analyzer.events:
if event['type'] == 'foul':
team = event['team']
if team not in team_stats:
team_stats[team] = {'total': 0, 'tactical': 0}
team_stats[team]['total'] += 1
# 模拟战术犯规统计
for i, detail in enumerate(results['details']):
team = detail['team']
if team in team_stats:
team_stats[team]['tactical'] += 1
for team, stats in team_stats.items():
print(f"{team}队:总犯规 {stats['total']} 次,战术犯规 {stats['tactical']} 次")
return results
if __name__ == "__main__":
main()
程序特点:
核心功能
- 解析比赛事件时间、球队、球员、位置等数据
- 根据预设条件判断是否属于战术犯规阻止反击
- 自动统计所有犯规和战术犯规次数
判定条件
- 对方在犯规前5秒内抢断球权且距离较远
- 犯规发生在对方进攻三区(x>60)
- 对方有快速推进的趋势
- 对方人数占优的情况(简化版)
使用方法
# 创建分析器
analyzer = FootballMatchAnalyzer()
# 添加比赛事件
analyzer.add_event(5, 30, "主队", "tackle", "张三", 70, 50, "中场抢断")
# 执行分析
results = analyzer.analyze_counterattack_fouls()
print(f"阻止反击次数: {results['counterattack_fouls']}")
扩展建议
- 可以接入实时比赛数据API
- 支持更多位置数据(如GPS定位数据)
- 添加比赛视频帧分析功能
- 引入机器学习模型提高判断准确性
运行这个程序会输出每场比赛中战术犯规阻止反击的具体次数和明细!