2009-10-16 73 views
0

我正在制作一个愚蠢的小游戏,将您的分数保存在highscores.txt文件中。用Python中的整数和文本对字符串排序

我的问题是整理线条。这是迄今为止我所拥有的。

也许一个python的字母数字分类器会有帮助吗?谢谢。

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() 
+0

尝试使用数组 – 2009-10-16 01:08:36

回答

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) 

的关键(;-)想法是要返回从每个项目的“排序键”(在这里,一条线)的功能。我试图以最简单的方式编写它:查看有多少前导数字,然后将它们全部变成一个int,然后返回该数字。

+0

谢谢亚历克斯!但是,当我在我的代码中插入该代码时,出现以下错误: SyntaxError:第24行文件read.py中的非ASCII字符'\ xc2',但未声明编码;有关详细信息,请参阅http://www.python.org/peps/pep-0263.html 任何想法是从哪里来的?再次感谢! – Nicholas 2009-10-16 01:19:33

+0

@Nicholas,在我发布的代码中没有非ASCII文本(特别是拉丁文-1中没有'0xc2',这将是一个带有旋律的大写字母-A),所以当然我绝对没有想法你是如何设法将你的代码加入_your_代码的。如果你不能在你自己的代码中找到它(?!),可能在一个问题中发布代码 - 但这与_this_问题确实无关,我似乎已经得到了令人满意的回答,所以我建议你让它一个_separate_问题。 – 2009-10-16 04:56:41

0

做一个简单的字符串排序您

new_score = str(score) + ".........." + name 

项目不会因为工作,例如STR(1000)< STR(500)。换句话说,1000会以字母数字排序前500。

亚历克斯的答案很好,它演示了使用排序键功能,但这里有另一种解决方案,它更简单一点,并具有可视对齐高分显示的附加优势。

你需要做的的成绩,从而(假设5位max和版本< 3.0)的最大尺寸的固定字段右对齐的数字:

new_score = "%5d........%s" % (score, name) 

或为Python版本3 .X:

new_score = "{0:5d}........{1}".format(score, name) 

对于每个NEW_SCORE追加到单词列表(你可以在这里使用一个更好的名字)和排序打印之前逆转。或者你可以使用bisect.insort库函数而不是做一个list.append。

而且,更Python形式大于

if file_exists == False: 

是:

if not file_exists: 
0

我估计出事了,当你从亚历克斯的答案粘贴,所以这里是在那里

排序代码

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将让你不必编写自己的解析器来恢复已保存的文件数据,如高分表。你可以把所有东西都塞进一本字典中,然后把所有东西全部弄回来。

请注意,我藏在一个版本号,高分保存格式的版本号。如果您更改了数据的保存格式,那么在其中输入版本号将会是一件非常好的事情。

+0

+1或yaml,如果你希望它更具人类可读性(并且不需要通过网络发送) – van 2009-10-16 05:57:07

+0

或者你可能是传统的并使用Python pickle模块。这可以保存任何Python数据类型,并且它包含在每个Python安装中。虽然不是很人性化。 – steveha 2009-10-16 23:56:56

0

你想要的可能是通常所说的“自然分类”。搜索“自然排序python”会得到很多结果,但是关于ASPN有一些很好的讨论。