在Python中用整数和文本排序字符串

2024-04-25 07:15:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我在做一个愚蠢的小游戏,在高分.txt文件。在

我的问题是把线分类。以下是我目前所掌握的情况。在

也许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()

Tags: thepathnameimporttxtifosmain
3条回答

我猜你粘贴Alex的答案时出了问题,所以这里是你的代码,里面有一个sort


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

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)

key(;-)的思想是创建一个函数,从每个项(这里是一行)返回“sorting key”。我试着用最简单的方法来写它:看看有多少个前导数字,然后把它们都转换成一个int,然后返回它。在

我想鼓励你把你的高分存储在一个更健壮的格式中。我特别建议使用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可以避免编写自己的解析器来从保存的文件(如高分表)中恢复数据。你可以把所有的东西都塞进字典里,然后轻而易举地把它们都找回来。在

注意,我塞进了一个版本号,你的高分保存格式的版本号。如果您曾经更改过数据的保存格式,那么有一个版本号将是一件非常好的事情。在

相关问题 更多 >