我无法弄清楚如何打印和排序我的csv文件,该文件涉及游戏中玩家的得分,姓名和时间,因此我可以打印前5个得分。
我一直在寻找stackoverflow一段时间,却找不到符合我要求的规格或符合我需要的规格的任何东西。因此,如果有人可以提供帮助,那就太好了。
我的csv文件如下所示:
Human,02:00,120
Joe,03:00,180
Alex,01:00,60
Jason,05:00,300
Liza,06:00,360
John,07:00,420
Mark,04:00,240
文件列为:Name, Time, RawTime. The RawTime
列是我要排序的列,以列出前5名中从最低到最高的时间
def addtoScoreboard(name, time, scores):
file = open("scores.csv", "a")
file.write("\n" + str(name) + "," + str(time) + "," + str(scores))
file.close
这就是我将分数添加到文本文件的方式。
如果有人可以帮助我对csv文件中的数据进行排序和打印,然后再将其添加到游戏中,那真的很酷。
答案 0 :(得分:1)
使用csv
模块。并将sorted()
与key
一起使用按时间排序。
例如:
import csv
with open(filename, "rU") as infile:
reader = csv.reader(infile)
data = [row for row in reader]
data = sorted(data, key=lambda x: int(x[-1])) #Sort by RawTime
with open(filename_1, "w") as outfile:
writer = csv.writer(outfile)
writer.writerows(data)
输出:
Alex,01:00,60
Human,02:00,120
Joe,03:00,180
Mark,04:00,240
Jason,05:00,300
Liza,06:00,360
John,07:00,420
答案 1 :(得分:1)
这应该做到。
import csv
li = []
#Import the csv as a dictionary
with open("out.csv") as infile:
reader = csv.DictReader(infile)
#Append all items to a list
for item in reader:
li.append(dict(item))
#Sort the list on Rawtime key
res = sorted(li, key=lambda x:int(x['RawTime']), reverse=True)
#Remove Rawtime from result
res = [ {i:item[i] for i in item if i!='RawTime'} for item in res[:5]]
print(res)
#Print without Name and List
for item in res:
print(','.join(list(item.values())))
#Write to a csv
keys = ['Name', 'Time']
with open('out.csv', 'w') as outfile:
writer = csv.DictWriter(outfile, keys)
#Write the header
writer.writeheader()
#Write the keys
for item in res:
writer.writerow(item)
所以,如果csv看起来像
Name,Time,RawTime
Human,02:00,120
Joe,03:00,180
Alex,01:00,60
Jason,05:00,300
Liza,06:00,360
John,07:00,420
Mark,04:00,240
输出将为
[{'Name': 'John', 'Time': '07:00'},
{'Name': 'Liza', 'Time': '06:00'},
{'Name': 'Jason', 'Time': '05:00'},
{'Name': 'Mark', 'Time': '04:00'},
{'Name': 'Joe', 'Time': '03:00'}]
输出的csv看起来像
Name,Time
John,07:00
Liza,06:00
Jason,05:00
Mark,04:00
Joe,03:00
打印时没有名称和列表的样子
John,07:00
Liza,06:00
Jason,05:00
Mark,04:00
Joe,03:00
答案 2 :(得分:1)
还有一个pandas库,尽管有点过头,但它允许您编写更简洁的代码:
import pandas as pd
df = pd.read_csv('input.csv', names=["Name", "Time", "RawTime"])
df = df.sort_values('RawTime')
df.to_csv('scores.csv', header=False, index=False)
答案 3 :(得分:0)
data_arr = []
with open("your_file.txt") as f:
for line in f.readlines():
name, time, raw_time = line.split(",")
data_arr.append((name, time, int(raw_time)))
data_arr = sorted(data_arr, key= lambda x: x[2])
with open("output_file.txt", "w") as f:
output = ""
for name, time, raw_time in data_arr:
output += (name + "," + time + "," + str(raw_time)) + "\n"
f.write(output)
答案 4 :(得分:0)
您可以将熊猫用作同一个
import pandas as pd
df = pd.read_csv('input_file.csv',header=None)
(df.sort_values([2],ascending=False) ## sorting high to low on column 2
.head(5) ## taking top 5
.sort_values([2],ascending=True) ## sorting low to high
.to_csv('scores.csv',header = False,index=False)) # exporting as csv