I have the snippet that sorts the contents of the text file. My problem is with the values after the scores as I am getting errors.
data = []
with open('data.txt') as f:
for line in f:
group, score, team = line.split(' ')
data.append((int(score), group.strip(), team.strip()))
data.sort(reverse=True)
print("Top Scores:")
for (score, group, team), _ in zip(data, range(3)):
print(f'{group} - {score} - {team}')
datafile.txt (3 columns GROUP, SCORE, TEAM NAME)
asdsd 1 dream team
swsds 3 never mind us
2sdsg 1 diehard
sklks 2 just cool
asedd 5 dont do it
Error: #-- If there are no spaces in the last column, it works just fine.
ValueError: too many values to unpack (expected 3).
Split the line by ReGex:
import re
...
for line in j:
group, score, team = re.split(r' (-?\d*\.?\d+) ', line.strip('\n').strip())
data.append((int(score), group.strip(), team.strip()))
print(data)
Gives:
[(1, 'asdsd', 'dream team'), (3, 'swsds', 'never mind us'), (1, '2sdsg', 'diehard'), (2, 'sklks', 'just cool')]