如何在文本文件中的每一行的开头添加序号

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何在文本文件中的每一行的开头添加序号相关的知识,希望对你有一定的参考价值。

我有一个存储在文件中的游戏的排行榜。文件格式如下:

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

我有这个代码按从升序到降序的顺序显示分数:

if ens == "s":
    print("
"+"LeaderBoard: "+"
")
    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()+"
")

输出:

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

我看过其他帖子,展示了如何显示序数,但我仍然不知道如何做到这一点。

答案

我觉得你被投票了,因为它看起来并不像你那么努力,而你没有说你尝试了什么,但无论如何你都去了:这样的事......

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()+"
")
另一答案

用下面的两行替换最后一行,序号用作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()+"
")

以上是关于如何在文本文件中的每一行的开头添加序号的主要内容,如果未能解决你的问题,请参考以下文章

从 RichTextBox 中的每一行获取文本?

如何在unix中的每一行末尾添加文本

如何将序数添加到文本文件中每一行的开头

如何将源文件名添加到 Spark 中的每一行?

如何将一行文本添加到目录中的多个文件

如何使用 Windows 批处理文件遍历文本文件中的每一行?