2013-03-04 49 views
1

外部文件的内容是这样的:如何从外部文件列出python中的数字?

Ricky, 12 
Sachin, 45 
Brian, 2 
Monty, 1 

我基本上想要做的是能在蟒蛇阅读本并能够为了它,所以它在底部和最高去最低分得分最高。

这里是我到目前为止的代码:

def SaveTopScores(): 
    return HiScores.rsplit('(',1)[1] 

    with open("HiScores.txt", "r")as file: 
    HiScoreslist = HiScores.read().splitlines() 

    HiScoreslist.sort() 

    HiScoreslist.sort(key=HiScore) 

    for HiScore in HiScoreslist: 
    print(HiScore) 

我还是Python的新手和确实需要帮助。请纠正我错在哪里,并告诉我我是否完全错误,如果有的话,我最好解决问题的方法是什么?

+2

是压痕是否正确?因为你正好在函数体的第一行返回,其余的都不会被执行。 – 2013-03-04 12:01:36

+0

感谢您的编辑:)我认为这是正确的。我通过做一个类似的事情做了一个练习,我从电影列表中订购了电影年,并且工作。所以现在我很困惑?如果你认为有更好的方法,请告诉我如何。我不知道该怎么办。 :( – PythonNovice 2013-03-04 12:04:41

+1

你做了一个rsplit,寻找一个左括号,那个字符不在输入文件中,那么你为什么要这样做? – Anthon 2013-03-04 12:06:41

回答

2

随着一些列表内涵:

with open("HiScores.txt") as hiscores: 
    scores = [line.split(',') for line in hiscores if line.strip()] 
scores = [(name.strip(), int(score)) for name, score in scores] 
scores.sort(key=lambda s: s[1], reversed=True) 

for name, score in scores: 
    print('{:<20} {:>10}'.format(name, score)) 

此:

  1. 打开该文件作为上下文管理器(with ... as ...),所以它会自动关闭
  2. 遍历文件拆分每行(提供的行不是空的)
  3. 将每个2-VA在该文件中略进入汽提柱和一个整数
  4. 排序在每个元组(分数)的第二个值的文件,扭转了结果(最高得分第一)
  5. 打印每个条目格式化(对准每个名左边是一个20个字符的区域,每个分数在10个字符的区域右边)。
+0

谢谢你的帮助。 :) – PythonNovice 2013-03-04 12:12:33

+0

(+1)检查空行:-) – FakeRainBrigand 2013-03-04 12:24:21

1

那么,有点像这样?

def scores(fn): 

    data = [] 
    with open(fn) as f: 
     for ln in f: 
      name, score = ln.strip().split(',') 
      data.append((int(score.strip()), name)) 

    for score, name in sorted(data, reversed=True): 
     print name, score 
+0

谢谢你的帮助。:) – PythonNovice 2013-03-04 12:12:14

0

没有太多的改变你的原代码,这应该工作。如果您需要解释任何部分,请告诉我。

with open("HiScores.txt", "r") as fin: 
    HiScores = fin.read().splitlines() 

HiScoresList = [] 

for score in HiScores: 
    name, score = score.split(', ') 
    score = int(score.strip()) 
    HiScoresList.append((name, score)) 

# Look at two score entries, and compare which score is larger 
def BestScore(a, b): 
    return cmp(b[1], a[1]) 

HiScoresList.sort(BestScore) 

for HiScore in HiScoresList: 
    print(HiScore) 

打印:

('Sachin', 45) 
('Ricky', 12) 
('Brian', 2) 
('Monty', 1) 
+0

感谢您的回应。以及我有点理解这是如何工作的,你是否可以向我解释什么是'好'? – PythonNovice 2013-03-04 12:18:11

+0

'with'的语法为'function_returning_file_object()as variable_to_hold_file_object:'。我只是叫我的变量,在这种情况下,'fin'或'fout'用于“文件输入”或“文件输出”。这比为一个变量创建名称想得更简单,只需要一行代码。把它叫做任何你喜欢的:-)只要确保你在同一个变量上调用'.read()'。 – FakeRainBrigand 2013-03-04 12:22:42

+0

好的谢谢你:) – PythonNovice 2013-03-04 12:24:10