本文目录导读:

我来为你设计一个Python案例,用于统计比赛中犯规战术阻止反击的次数。
场景设定
假设我们有一个足球比赛的数据流,包含比赛中的事件,我们需要识别"犯规战术阻止反击"的情况。
代码实现
import pandas as pd
from datetime import datetime, timedelta
import random
class CounterAttackAnalyzer:
def __init__(self):
# 犯规战术特征阈值
self.time_threshold = 30 # 秒,距反击开始的时间窗口
self.field_position_weight = 0.3 # 场地位置权重
self.time_weight = 0.4 # 时间权重
self.situation_weight = 0.3 # 比赛情况权重
def calculate_tactical_foul_score(self, event, game_context):
"""
计算犯规战术的可能性得分
"""
score = 0
# 1. 时间因素:犯规发生在反击开始后多久
if event['time_since_counter'] <= self.time_threshold:
time_score = 1 - (event['time_since_counter'] / self.time_threshold)
score += time_score * self.time_weight
# 2. 场地位置因素
if 'attack_zone' in event:
if event['attack_zone'] in ['final_third', 'middle_third_adv']:
score += (1 - event['distance_to_goal'] / 100) * self.field_position_weight
# 3. 比赛情况因素
if event['was_possession_gaining']: # 是否阻止了得分机会
score += self.situation_weight * 0.7
elif event['was_dangerous_attack']: # 是否是危险进攻
score += self.situation_weight * 0.9
# 4. 犯规严重程度
if event['foul_type'] == 'professional_foul':
score += 0.5
elif event['foul_type'] == 'stopping_counter':
score += 0.8
return min(score, 1.0) # 确保不超过1
def is_counter_attack_foul(self, event, game_context):
"""
判断是否为犯规战术阻止反击
"""
# 基本条件检查
if not event['is_foul']:
return False
# 检查是否在反击过程中
if not event['in_counter_attack']:
return False
# 计算犯规战术得分
foul_score = self.calculate_tactical_foul_score(event, game_context)
# 判断是否为战术犯规
return foul_score >= 0.6 # 阈值设定
def analyze_match(self, events_data):
"""
分析整场比赛中的犯规战术阻止反击次数
"""
counter_attack_fouls = []
normal_fouls = []
# 构建比赛上下文
game_context = self._build_game_context(events_data)
for event in events_data:
if event['is_foul']:
if self.is_counter_attack_foul(event, game_context):
counter_attack_fouls.append(event)
# 如果阻止了明显得分机会,可能加罚
if event['blocked_clear_chance']:
event['additional_punishment'] = True
else:
normal_fouls.append(event)
return {
'total_fouls': len(events_data[events_data['is_foul']]),
'counter_attack_fouls': len(counter_attack_fouls),
'normal_fouls': len(normal_fouls),
'blocked_clear_chances': sum(1 for e in counter_attack_fouls if e['blocked_clear_chance']),
'details': counter_attack_fouls
}
def _build_game_context(self, events):
"""构建比赛上下文"""
context = {
'score_difference': events.iloc[-1]['home_score'] - events.iloc[-1]['away_score'],
'home_team': events.iloc[0]['home_team'],
'away_team': events.iloc[0]['away_team'],
'match_time': events.iloc[-1]['game_time']
}
# 分析比赛阶段
if context['match_time'] < 45:
context['match_stage'] = 'first_half'
elif context['match_time'] < 90:
context['match_stage'] = 'second_half'
else:
context['match_stage'] = 'extra_time'
return context
def visualize_analysis(self, analysis_result):
"""可视化分析结果"""
import matplotlib.pyplot as plt
labels = ['战术犯规', '普通犯规']
sizes = [analysis_result['counter_attack_fouls'],
analysis_result['normal_fouls']]
colors = ['#FF6B6B', '#4ECDC4']
plt.figure(figsize=(10, 6))
plt.pie(sizes, labels=labels, colors=colors, autopct='%1.1f%%',
startangle=90, explode=(0.05, 0))
plt.title(f'犯规类型分布 - {analysis_result.get("match", "比赛")}')
plt.axis('equal')
plt.show()
# 打印摘要
print("="*50)
print("犯规战术阻止反击分析报告")
print("="*50)
print(f"总犯规次数: {analysis_result['total_fouls']}")
print(f"战术犯规阻止反击: {analysis_result['counter_attack_fouls']}次")
print(f" 其中阻止明显得分机会: {analysis_result['blocked_clear_chances']}次")
print(f"普通犯规: {analysis_result['normal_fouls']}次")
# 示例数据生成器
def generate_sample_match_events():
"""生成模拟比赛数据"""
events = []
match_time = []
# 模拟90分钟的比赛事件
for minute in range(1, 91):
# 每2-5分钟可能有一次事件
if random.random() < 0.3:
event = {
'minute': minute,
'is_foul': False,
'in_counter_attack': False,
'time_since_counter': 0,
'attack_zone': 'defensive_third',
'distance_to_goal': random.randint(0, 100),
'was_possession_gaining': False,
'was_dangerous_attack': False,
'foul_type': 'none',
'blocked_clear_chance': False,
'home_score': random.randint(0, 1),
'away_score': random.randint(0, 1)
}
# 随机生成事件类型
event_type = random.random()
if event_type < 0.15: # 15%概率为犯规
event['is_foul'] = True
event['foul_type'] = random.choice(['regular', 'professional_foul', 'stopping_counter'])
event['in_counter_attack'] = random.random() < 0.4
if event['in_counter_attack']:
event['time_since_counter'] = random.randint(1, 30)
event['attack_zone'] = random.choice(['middle_third_adv', 'final_third'])
event['was_dangerous_attack'] = random.random() < 0.5
event['was_possession_gaining'] = random.random() < 0.4
event['blocked_clear_chance'] = random.random() < 0.3
elif event_type < 0.25: # 10%概率为射门
event['attack_zone'] = 'final_third'
event['was_dangerous_attack'] = True
# 更新比分
if random.random() < 0.01: # 1%概率进球
if random.random() < 0.5:
event['home_score'] += 1
else:
event['away_score'] += 1
events.append(event)
return events
# 主程序
def main():
# 生成模拟数据
print("生成模拟比赛数据...")
match_events = generate_sample_match_events()
# 转换为DataFrame
import pandas as pd
df = pd.DataFrame(match_events)
# 创建分析器
analyzer = CounterAttackAnalyzer()
# 进行比赛分析
print("开始分析比赛...")
result = analyzer.analyze_match(df)
# 输出结果
analyzer.visualize_analysis(result)
# 详细输出
print("\n战术犯规详情:")
for i, foul in enumerate(result['details'], 1):
if 'additional_punishment' in foul and foul['additional_punishment']:
punishment_note = " [可能加罚]"
else:
punishment_note = ""
print(f"{i}. 第{foul['minute']}分钟 - 犯规类型: {foul['foul_type']}"
f" - 位置: {foul['attack_zone']}"
f" - 时间窗口: {foul['time_since_counter']}秒"
f"{punishment_note}")
return result
if __name__ == "__main__":
result = main()
功能说明
这个系统能够:
- 识别战术犯规:通过分析犯规的时间、位置和比赛情况
- 评估犯规严重程度:判断是否阻止了明显得分机会
- 生成详细报告:统计分析和可视化展示
- 支持实时判断:为裁判和教练提供决策参考
使用建议
- 可以根据实际比赛调整权重和阈值
- 可以扩展更多数据源(如球员位置、跑动轨迹等)
- 可以结合视频回放进行更精确的判断
这个系统既能帮助裁判更准确判罚,也能帮助教练分析对手的战术犯规习惯。