Что это за ошибка и как, следовательно, отображать 5 лучших результатов из файла .csv? - PullRequest
0 голосов
/ 05 января 2020

Я пишу игру в кости, и после ее окончания имена обоих игроков сохраняются в файле leaderboard2.csv. С leaderboard2.csv я пытаюсь отобразить 5 лучших результатов. Как это сделать?

Я смотрел много уроков, но все они используют файлы .txt, тогда как у меня есть файл .csv (в Excel) для списка лидеров.

Я используя python 3.3.4 и мой код прямо ниже:

import operator
with open("leaderboard2.csv", "r") as l:
    try:
        sort_key = operator.itemgetter(0)
        split_lines = (line.split(None, 1) for line in l) # splits the file into it's individual lines
        numeric_lines = ((int(line[0]), line[1]) for line in split_lines) # splits the numbers and the letters
        score = sorted(numeric_lines, key=sort_key, reverse=True) # sorts the numbers and letters into the opposite order
        leader_board1 = (score[0])
        leader_board2 = (score[1])
        leader_board3 = (score[2])
        leader_board4 = (score[3])
        leader_board5 = (score[4]) # gets the fifth line
    except IndexError:
        leader_board1 = '\n'
        leader_board2 = '\n'
        leader_board3 = '\n'
        leader_board4 = '\n'
        leader_board5 = '\n'
        print("--------- LEADER BOARD ---------")
        sys.stdout.write("FIRST PLACE: "), print(*leader_board1, sep=" points: ", end='')
        sys.stdout.write("SECOND PLACE: "), print(*leader_board2, sep=" points: ", end='\n')
        sys.stdout.write("THIRD PLACE: "), print(*leader_board3, sep=" points: ", end='')
        sys.stdout.write("FOURTH PLACE: "), print(*leader_board4, sep=" points: ", end='')
        sys.stdout.write("FIFTH PLACE: "), print(*leader_board5, sep=" points: ", end='')
        input(">>> ")

Вот ошибка, которую я получаю:

numeric_lines = ((int(line[0]), line[1]) for line in split_lines) # splits the numbers and the letters
ValueError: invalid literal for int() with base 10: 'ok,46'

Кстати, ok,46 - первая строка в файле .csv (ok - имя пользователя, 46 - оценка)

1) Что означает эта ошибка и как ее исправить?

2) Как еще можно отобразить 5 лучших результатов из файла .csv?

Мой файл cvs выглядит следующим образом:

k,32
no,75
test,33
example,65
a,10
l,50

Заранее спасибо.

1 Ответ

0 голосов
/ 05 января 2020

Вот решение с использованием Python 3.6+ и его стандартных модулей:

import csv
from pathlib import Path
from collections import Counter

csvfile = Path('leaderboard2.csv')

with csvfile.open() as f:
    scores = Counter(dict(csv.reader(f)))

    # convert scores into integers
    # (there are better ways but I'm being didactic)
    for name in scores:
        scores[name] = int(scores[name])

    # list the top five
    for name, score in scores.most_common(5):
        print(f'{name}: {score}')

Вот альтернативная версия:

import csv
from pathlib import Path
from collections import Counter

csvfile = Path('leaderboard2.csv')

scores = Counter()

with csvfile.open() as f:
    for name,score in csv.reader(f):

    # convert score into integer
    score = int(score)
    scores[name] = score

# list the top five
for name, score in scores.most_common(5):
    print(f'{name}: {score}')

А вот версия, которая будет работать с более ранними версиями Python 3:

import csv
from collections import Counter

scores = Counter()

with open('leaderboard2.csv') as f:
    for name,score in csv.reader(f):

    # convert score into integer
    score = int(score)
    scores[name] = score

# list the top five
for name, score in scores.most_common(5):
    print('%s: %s' % (name, score))

Я надеюсь, что это поможет в качестве отправной точки.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...