在Python中对包含整数和文本的字符串排序
我正在做一个简单的小游戏,它会把你的分数保存在一个叫做highscores.txt的文件里。
我遇到的问题是如何对这些分数进行排序。现在我有了一些代码。
也许可以用一个字母数字排序的工具来帮助我?谢谢。
import os.path
import string
def main():
#Check if the file exists
file_exists = os.path.exists("highscores.txt")
score = 500
name = "Nicholas"
#If the file doesn't exist, create one with the high scores format.
if file_exists == False:
f = open("highscores.txt", "w")
f.write('Guppies High Scores\n1000..........Name\n750..........Name\n600..........Name\n450..........Name\n300..........Name')
new_score = str(score) + ".........." + name
f = open("highscores.txt", "r+")
words = f.readlines()
print words
main()
5 个回答
0
我想你在从Alex的回答中复制代码时出了点问题,所以这里是你代码的一个版本,里面加了排序的功能。
import os.path
def main():
#Check if the file exists
file_exists = os.path.exists("highscores.txt")
score = 500
name = "Nicholas"
#If the file doesn't exist, create one with the high scores format.
if file_exists == False:
f = open("highscores.txt", "w")
f.write('Guppies High Scores\n1000..........Name\n750..........Name\n600..........Name\n450..........Name\n300..........Name')
new_score = str(score) + ".........." + name +"\n"
f = open("highscores.txt", "r+")
words = f.readlines()
headers = words.pop(0)
def anotherway(aline):
score=""
for c in aline:
if c.isdigit():
score+=c
else:
break
return int(score)
words.append(new_score)
words.sort(key=anotherway, reverse=True)
words.insert(0, headers)
print "".join(words)
main()
1
我想鼓励你把你的高分记录存储在一种更可靠的格式中。我特别建议使用JSON格式。
import simplejson as json # Python 2.x
# import json # Python 3.x
d = {}
d["version"] = 1
d["highscores"] = [[100, "Steve"], [200, "Ken"], [400, "Denise"]]
s = json.dumps(d)
print s
# prints:
# {"version": 1, "highscores": [[100, "Steve"], [200, "Ken"], [400, "Denise"]]}
d2 = json.loads(s)
for score, name in sorted(d2["highscores"], reverse=True):
print "%5d\t%s" % (score, name)
# prints:
# 400 Denise
# 200 Ken
# 100 Steve
使用JSON格式可以避免你自己写解析器来从保存的文件中恢复数据,比如高分榜。你只需要把所有内容放进一个字典里,就能轻松地把它们取出来。
注意,我在这里加了一个版本号,也就是你高分保存格式的版本号。如果你将来改变数据的保存格式,里面有个版本号会非常有用。
4
在执行 words = f.readlines()
之后,可以尝试类似下面的代码:
headers = words.pop(0)
def myway(aline):
i = 0
while aline[i].isdigit():
i += 1
score = int(aline[:i])
return score
words.sort(key=myway, reverse=True)
words.insert(0, headers)
这里的关键点是要写一个函数,这个函数能从每一项(在这里是每一行)中提取出“排序的关键”。我想尽量用最简单的方式来写:先看看每行开头有多少个数字,然后把这些数字都转换成整数,最后把这个整数返回。