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

Python读取文本文件提取Top5最高分数及玩家名的实现求助

解决方案:读取并筛选分数最高的5位玩家

先修正原写入代码的潜在问题

你当前的代码里,score和score2是字符串类型,直接比较会出现逻辑错误(比如字符串"100"会被判定为小于"99",因为按字符顺序比对)。先把这部分代码修正,确保写入的获胜者是正确的:

name = input("Player 1 name: ")
name2 = input("Player 2 name: ")
# 转换为整数,保证分数比较逻辑正确
score = int(input("Player 1 score: "))
score2 = int(input("Player 2 score: "))

# 用with语句自动管理文件,避免手动关闭的遗漏问题
with open("CH30.txt", "a") as text_file:
    # 判断文件是否为空,非空则先换行再写入新内容
    text_file.seek(0)
    if text_file.read():
        text_file.write("\n")
    # 写入获胜者信息
    if score > score2:
        text_file.write(f"{name} wins with {score} points")
    else:
        text_file.write(f"{name2} wins with {score2} points")

读取文件并筛选Top5高分玩家

下面是实现读取文件、解析玩家数据、筛选前5高分的代码:

def get_top_players(file_path, top_n=5):
    player_list = []
    with open(file_path, "r") as f:
        for line in f:
            line = line.strip()
            if not line:
                continue  # 跳过空行
            # 按固定格式拆分每行内容
            split_part = line.split(" wins with ")
            if len(split_part) != 2:
                continue  # 跳过格式错误的无效行
            name = split_part[0].strip()
            # 提取分数部分并转换为整数
            score_str = split_part[1].replace(" points", "").strip()
            try:
                score = int(score_str)
                player_list.append( (name, score) )
            except ValueError:
                continue  # 跳过分数不是整数的行
    
    # 按分数降序排序,取前top_n个
    player_list.sort(key=lambda x: x[1], reverse=True)
    return player_list[:top_n]

# 调用函数并打印结果
top_5_players = get_top_players("CH30.txt")
print("分数最高的5位玩家:")
for rank, (name, score) in enumerate(top_5_players, 1):
    print(f"{rank}. {name}:{score}分")

代码说明

  • 用with语句操作文件,无需手动关闭,更安全稳定。
  • 加入了异常处理和格式校验,避免因空行、错误格式导致程序崩溃。
  • 用lambda表达式指定排序规则,直接按分数降序排列,逻辑直观。
  • 最终返回并打印排名前5的玩家信息。

整合建议

你可以把这段筛选代码放到骰子游戏的结束环节,当所有对局完成后,调用get_top_players函数即可输出高分榜。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 23:25:20