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

Python读取分数文件时仅获取数字首字符而非完整数值的问题求助

问题描述

我有一个文本文件,每行内容格式为「PlayerName wins with x points」,玩家名称与分数长度各不相同。需要编写Python代码读取该文件并输出分数最高的前5名玩家。但当前代码运行后出现异常,比如分数为123的Martin排在最后,推测是读取时仅获取了数字的第一位。

原错误代码

name = str(input("Player 1 name"))
name2 = str(input("Player 2 name"))
score = str(input("Player 1 score"))
score2 = str(input("Player 2 score"))
text_file = open("CH30.txt", "r+")
if score > score2:
    content = text_file.readlines(30)
    if len(content) > 0 :
        text_file.write("\n")
    text_file.write(name)
    text_file.write (" wins with ")
    text_file.write (score)
    text_file.write (" points")
else:
    content = text_file.readlines(30)
    if len(content) > 0 :
        text_file.write("\n")
    text_file.write (name2)
    text_file.write (" wins with ")
    text_file.write (score2)
    text_file.write (" points")


text_file = open('CH30.txt.', 'r')
Lines = text_file.readlines()
PlayersScores = []

# read each line get the player name and points 
for line in Lines:
    # split the line into list of strings
    line = line.split(" ")
    # removing \n from last element
    line[-1] = line[-1].replace("\n", "")
    print(line)
    # find player name position
    playerName = line.index("wins") - 1
    # find points position
    points = line.index("points") - 1
    points = int(points)
    # add the tuple (playerName, points) in a list
    PlayersScores.append((line[playerName], line[points]))
# descending order sort by player score
PlayersScores = sorted(PlayersScores, key=lambda t: t[1], reverse=True)

# get the first 5 players
print("Highest Scores:\n")
for i in range(5):
    print(str(i+1) + ". " + PlayersScores[i][0] + " " + PlayersScores[i][1] + " points")

问题原因

  1. 分数提取逻辑完全错误:代码中points = line.index("points") - 1获取的是分数在分割后列表中的索引位置,随后将这个索引转为整数,再用line[points]取元素——这相当于用索引的数值去匹配列表位置,完全偏离了提取分数的目标,导致多位数分数被错误读取。
  2. 字符串比较分数:原代码用字符串类型比较分数(score > score2),会出现"123" < "54"的错误结果,因为字符串是按字符逐个对比的。
  3. 文件操作问题:未正确关闭文件,且读取文件时文件名多了一个点(CH30.txt.),会导致文件找不到。
  4. 玩家名提取局限:仅支持单字玩家名,遇到带空格的玩家名会提取错误。

修正后的代码

# 输入处理:确保分数为整数
name = input("Player 1 name: ")
name2 = input("Player 2 name: ")
try:
    score = int(input("Player 1 score: "))
    score2 = int(input("Player 2 score: "))
except ValueError:
    print("请输入有效的数字分数")
    exit()

# 写入文件:用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")

# 读取并处理文件内容
PlayersScores = []
with open('CH30.txt', 'r') as text_file:
    for line in text_file:
        line = line.strip()
        if not line:
            continue  # 跳过空行
        
        parts = line.split(" ")
        # 提取玩家名:"wins"之前的所有内容(支持带空格的名字)
        wins_idx = parts.index("wins")
        player_name = " ".join(parts[:wins_idx])
        # 提取分数:"with"之后的第一个元素
        with_idx = parts.index("with")
        try:
            player_score = int(parts[with_idx + 1])
            PlayersScores.append((player_name, player_score))
        except ValueError:
            print(f"跳过无效行:{line}")
            continue

# 按分数降序排序
PlayersScores.sort(key=lambda x: x[1], reverse=True)

# 输出前5名(如果不足5名则输出全部)
print("Highest Scores:\n")
top_count = min(5, len(PlayersScores))
for i in range(top_count):
    print(f"{i+1}. {PlayersScores[i][0]} {PlayersScores[i][1]} points")

关键修正说明

  • 分数类型修正:输入分数时直接转为整数,用数值比较替代字符串比较,避免排序错误。
  • 文件管理优化:使用with语句自动处理文件打开/关闭,避免资源泄漏。
  • 正确提取数据:玩家名取"wins"之前的所有内容,支持带空格的名称;分数取"with"之后的元素,转为整数后存入列表。
  • 鲁棒性提升:增加异常处理,跳过无效行,避免非数字分数导致程序崩溃。
  • 边界处理:输出前5名时判断列表长度,避免索引越界。

内容的提问来源于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:40:26