如何在文本文件的每行开头添加序数

时间:2019-04-21 16:18:17

标签: python python-3.x leaderboard ordinals

我在文件中存储了游戏排行榜。该文件的格式为:

bob has 46 points fred has 0 points leo has 27 points

我有这段代码按升序到降序显示分数:

if ens == "s":
    print("\n"+"LeaderBoard: "+"\n")
    f = open("scores.txt","r")
    lines = list(f) #create a list of strings
    f.close() #don't forget to close our files when we're done. It's good practice.
    modified_lines = [] #empty list to put our modified lines in (extracted number, original line)
    for line in lines: #iterate over each line
        if line.strip(): #if there's anything there after we strip away whitespace
            score = line.split(' ')[2] #split our text on every space and take the third item
            score = int(score) #convert the string of our score into a number
            modified_lines.append([score, line]) #add our modified line to modified_lines

    #sort our list that now has the thing we want to sort based on is first
    sorted_modified_lines = sorted(modified_lines, reverse = True )

    #take only the string (not the number we added before) and print it without the trailing newline.
    for line in sorted_modified_lines: print(line[1].strip()+"\n")

输出:

bob has 46 points leo has 27 points fred has 0 points

我想要的是将分数显示在分数前面,如下所示:

1st. bob has 46 points 2nd. leo has 27 points 3rd. fred has 0 points

我看过另一篇文章,该文章显示了如何显示序数,但是我仍然不知道该怎么做。

2 个答案:

答案 0 :(得分:1)

我认为您会感到沮丧,因为它看起来并不像您尝试的那么努力,您没有说您尝试做的事情,但是无论如何,您还是要这样做:类似的事情。 ..

def ordinal_string(i):
   if i >= 10 and i <= 20:
      suffix = 'th'
   else:
     il = i % 10
     if il == 1:
        suffix = 'st'
     elif il == 2:
        suffix = 'nd'
     elif il == 3:
        suffix = 'rd'
     else:
        suffix = 'th'
   return str(i) + suffix + '. '

然后:

for i, line in enumerate(sorted_modified_lines): print(ordinal_string(i+1) + line[1].strip()+"\n")

答案 1 :(得分:1)

将最后一行替换为下面的两行,将序号从here引用作为参考

suf = lambda n: "%d%s"%(n,{1:"st",2:"nd",3:"rd"}.get(n if n<20 else n%10,"th"))

for index, line in enumerate(sorted_modified_lines): print(suf(index + 1) + '. ' + line[1].strip()+"\n")