从文本文件中读取高分并排名

Read high scores from text file and rank

我有一个数学程序,可以对球员进行评分并将他们的姓名和分数输入到文本文件中。

我可以从文本文件中获取分数,但无法弄清楚如何识别每个部分:名称为字符串,分数为 int。

它是这样输入到文件中的:

playername: 8

将玩家姓名和分数输入文本文件的代码是:(我已将分数设置为全局变量,它是从较早的函数中提取的。

# write score to text document
def scores():
    score = Pname + ": " +str(points)
    scoreFile = open("score.txt", "a")
    scoreFile.write(score + "\n")
    scoreFile.close()
    print("Your scores have been saved to the high score chart.\n")
close()

我试过多种方法把它弄出来只是给我数据。我正在努力将它分成名称和分数,然后按分数降序排列。

def highscore():
# --------------------------------------------
# sort scores from text file here
try:
    scores = open("score.txt", "r")
    for line in scores.readlines():
        line_parts = line.split(": ")
        if len(line_parts) > 1:
            line_parts = line_parts[-1].split("\n")
            score = line_parts[0]
        print(sorted(score))
except Exception:
    pass
# --------------------------------------------
close()

这只是显示分数如下:

['7']
['4']
['9']
['1']

我需要它看起来像:

['Player 1: 9']
['Player 2: 7']
['Player 3: 4']
['Player 4: 1']

试试这个: 创建排序方法并将整个列表提供给排序方法。

def highscore():
# --------------------------------------------
# sort scores from text file here
try:
   scores = open("score.txt", "r")
   x = []   # place all your processed lines in here
   for line in scores.readlines():
       line_parts = line.split(": ")
       if len(line_parts) > 1:
           line_parts[-1] = line_parts[-1].replace("\n", "")
           x.append(line_parts)   # sorting uses lists
   print(sorted(x, key=sortByScore))   # get this out of for loop
except Exception:
    pass
# --------------------------------------------
close()

def sortByScore(inputPlayerScore):
    return inputPlayerScore[1]

更新:

我已经更新了代码并进行了测试。现在可以了。我一直在使用 python2.7

更新:2

很简单。只需将 print 命令移出 for 循环,您将获得所需的输出。