我有一个问题,排序一个大的文本文件。 文本文件看起来像这样:如何使用python根据最后一列的字符串值对文本文件进行排序?
word, two words, 15, 988, anotherword, 99
also some words, nope, 20, 122, characters, 39
text, words words, 10, 300, more words, 9
每条线的一端有一个换行符(\ n)的。
我想根据最后一列中的整数对文件进行降序排序。
我用下面的代码,我发现这里的计算器:
from operator import itemgetter
with open ('sourcefile.txt') as fin:
lines = [line.split(',') for line in fin]
lines.sort(key=itemgetter(5),reverse=True)
with open('sortedfile.txt', 'w') as fout:
for el in lines:
fout.write('{0}\n'.format(','.join(el)))
我这个解决方案获得的问题是,脚本是按字母顺序排序。像这样:
word, two words, 15, 988, anotherword, 99
text, words words, 10, 300, more words, 9
also some words, nope, 20, 122, characters, 39
什么可能是这个问题的实际解决方案?
这工作就像一个魅力。我花了一段时间才明白你做了什么,但我想我现在就做!谢谢。 –
@DavidDeSmedt不要写“谢谢”意见,请点击左侧灰色的勾号来接受答案。您可以在[帮助]或小型[游览]页面了解有关本网站如何工作的更多信息。 –