You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

2018世界杯进球数统计Python字典实现及猜谜功能完善求助

2018世界杯进球统计问答函数实现方案

完整代码实现

import random

def Quiz():
    # 初始化进球统计字典
    goal_stats = {}
    
    # 读取文件并统计各国进球数
    with open('worldcup2018_goals.txt', 'r', encoding='utf-8') as f:
        for line in f:
            line = line.strip()
            if not line:
                continue  # 跳过空行
            # 分割行数据,格式为playername;country;minute;
            parts = line.split(';')
            if len(parts) >= 2:
                country = parts[1].strip()
                # 更新统计字典
                goal_stats[country] = goal_stats.get(country, 0) + 1
    
    # 检查数据是否足够进行问答
    if len(goal_stats) < 2:
        print("数据不足,无法生成问答")
        return
    
    # 随机选取两个不同的国家
    country_a, country_b = random.sample(list(goal_stats.keys()), 2)
    
    # 展示问答问题
    print("请猜测以下两个国家中,哪个在2018世界杯进球更多?")
    print(f"A: {country_a}")
    print(f"B: {country_b}")
    
    # 获取有效用户输入
    while True:
        user_answer = input("请输入你的答案(A/B):").strip().upper()
        if user_answer in ('A', 'B'):
            break
        print("输入无效,请输入A或B")
    
    # 判断答案正确性
    user_country = country_a if user_answer == 'A' else country_b
    if goal_stats[country_a] > goal_stats[country_b]:
        correct_country = country_a
    elif goal_stats[country_b] > goal_stats[country_a]:
        correct_country = country_b
    else:
        print(f"平局!两个国家进球数均为{goal_stats[country_a]}")
        return
    
    if user_country == correct_country:
        print(f"回答正确!{correct_country}进球{goal_stats[correct_country]}个,{country_b if correct_country == country_a else country_a}进球{goal_stats[country_b if correct_country == country_a else country_a]}个")
    else:
        print(f"回答错误。正确答案是{correct_country}({goal_stats[correct_country]}球),你选择的{user_country}仅进球{goal_stats[user_country]}个")

# 执行问答函数
Quiz()

关键模块说明

1. 进球统计字典构建

  • 使用with open语句安全读取文件,自动处理文件关闭
  • 逐行处理时先去除首尾空白,跳过空行避免无效数据
  • 用split(';')分割每行内容,提取索引1的字段作为国家名称
  • 利用字典的get方法简化统计逻辑:goal_stats.get(country, 0) + 1,如果国家不存在则默认返回0,再加1实现计数

2. 用户问答逻辑

  • 用random.sample从字典键中随机选取两个不重复的国家,保证每次问答的随机性
  • 循环获取用户输入,只接受A/B的有效输入,避免程序崩溃
  • 增加平局判断逻辑,当两个国家进球数相同时直接提示结果
  • 对比用户选择的国家和进球数更多的国家,给出清晰的对错反馈

注意事项

  • 确保txt文件路径正确,若文件不在当前脚本目录,需修改open函数中的文件路径
  • 若文件存在格式异常的行,代码会自动跳过(仅当分割后至少有2个字段时才处理),保证程序健壮性

内容的提问来源于stack exchange,提问作者Jacob

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 05:32:36