首页 > 解决方案 > 在带有更多空格的文本文件中对数据进行排序会在 python 中产生错误

问题描述

我有对文本文件内容进行排序的片段。我的问题是得分后的值,因为我遇到了错误。

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 列 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

错误:#-- 如果最后一列没有空格,则可以正常工作。

ValueError: too many values to unpack (expected 3). 

标签: pythonpython-3.xsortingtext

解决方案


用正则表达式分割行:

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)

给出:

[(1, 'asdsd', 'dream team'), (3, 'swsds', 'never mind us'), (1, '2sdsg', 'diehard'), (2, 'sklks', 'just cool')]

推荐阅读