简体   繁体   English

我试图在 python 中做一些代码,它读取一个文本文件并挑选出数字最大的 5 行并打印它们

[英]Im trying to do some code in python that reads a text file and picks out the 5 lines with the highest number and prints them

i have an assignment coming up in which i have to code a dice game.我有一项任务即将完成,我必须编写一个骰子游戏。 its multiplayer random luck with gambling points and etc它的多人随机运气与赌博点数等

one of the things its asking for though is to save the winning players name and their score into a text file and at the end print the five highest scores in the text file with the five players names, ive got the code so that it saves the players name and score along with some text but have absolutely no idea on how to read the whole text file and and pick out lines that have the 5 largest integers and print them它要求的一件事是将获胜玩家的名字和他们的分数保存到一个文本文件中,最后用五个玩家的名字在文本文件中打印五个最高分数,我得到了代码,这样它就可以保存玩家姓名和分数以及一些文本,但完全不知道如何阅读整个文本文件并挑选出具有 5 个最大整数的行并打印它们

` `

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")


` `

the full game is not attached as I'm at my dads house currently and forgot to bring my usb stick any help on how to do this would be much appreciated:)完整的游戏没有附加,因为我目前在我爸爸的房子里,忘记带我的 usb 棍子任何关于如何做到这一点的帮助将不胜感激:)

If your data in file has this format:如果文件中的数据具有以下格式:

Player1 wins with 30 points
Player2 wins with 40 points
Player3 wins with 85 points
Player5 wins with 45 points
Player7 wins with 10 points
Player6 wins with 80 points
Player4 wins with 20 points
Player9 wins with 90 points
Player8 wins with 70 points
Player11 wins with 120 points
Player10 wins with 15 points

and there is no space in the first line of the file, because you have text_file.write("\n") written in the first line.并且文件的第一行没有空格,因为你在第一行写了text_file.write("\n") Please add it at the end of the line, ie the last file write.请在行尾添加,即最后一个文件写入。

For example:例如:

text_file.write(name)
text_file.write (" wins with ")
text_file.write (score)
text_file.write (" points")
text_file.write("\n")

Here is how to get the 5 highest scores of the file:以下是如何获得文件的 5 个最高分数:

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
    # 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")

Output example: Output 示例:

Highest Scores:

1. Player11 120 points
2. Player9 90 points
3. Player3 85 points
4. Player6 80 points
5. Player8 70 points

First of all, you should read the file to a list of lines.首先,您应该读取文件的行列表。 If you don`t know how to do this, check:如果您不知道如何执行此操作,请检查:
How to read a file line-by-line into a list? 如何将文件逐行读取到列表中?

Next, you have to sort the lines.接下来,您必须对行进行排序。 We can use lambda to achieve it.我们可以使用lambda来实现。 Assuming, that the single line looks like this:假设单行看起来像这样:
"Rick wins with 98 points"

Sorting function would look like this:排序 function 看起来像这样:
scores.sort(key= lambda x: int(x.split(" ")[3]))

Then, you just need to slice the last five elements.然后,您只需要对最后五个元素进行切片。

Please note, this solution is prone to many errors, as you use the file in human-readable format.请注意,此解决方案容易出现许多错误,因为您使用的是人类可读格式的文件。 What's easily readable for us, is often hard to read by computer (and vice versa).对我们来说容易阅读的内容通常很难被计算机阅读(反之亦然)。 So, if you don't want to use the file as a bedtime reading, consider using some formats, that are easier to parse - ie CSV因此,如果您不想将该文件用作睡前读物,请考虑使用一些更易于解析的格式 - 即 CSV

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我的代码缺少一些我试图退出文件的行 - My code is missing some of the lines im trying to get out of a file 我如何编写一个算法,该算法读取三个数字并在python中按升序将其打印出来 - How do i write an algorithm that reads three numbers and prints them out in ascending order in python 尝试将某个值打印到 txt 文件的 python 代码 - Trying to python code that prints out a certain value to a txt file 我正在尝试使用 python 从 html 网站中提取一些数据 - im trying to extract some data out of html website using python 看不懂一些读取文件的代码行 - Don't understand some lines of code that reads a file 创建一个函数,该函数从文本文件中读取所有代码行,并将每一行放入元组中。 -Python 3 - Create a function which reads all lines of code from text file and put each line into tuples. -Python 3 python 代码不打印文本文件“c” - The python code does not prints the text file 'c' 如何创建一个从文本文件中读取数据并将其打印在两个不同部分的程序 - how to create a program that reads the data from the text file and prints it out in two different sections 如何在python中编写正则表达式,以选择所有以特定数字开头的字符串 - How do you write a regex in python which picks out all strings beginning with a specific number Python - 正则表达式排除文件中的某些行 - Python - Regex to exclude some lines out of file
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM