概述
import sysfrom functools import partialfrom heapq import mergefrom tempfile import TemporaryFile# define sorting criteriadef second_column(line, default=float("inf")):
try:
return int(line.split(";", 2)[1]) # use int() for numeric sort
except (IndexError, ValueError):
return default # a key for non-integer or non-existent 2nd column# sort lines in small batches, write intermediate results to temporary filessorted_files = []nbytes = 1 << 20 # load around nbytes bytes at a timefor lines in iter(partial(sys.stdin.readlines, nbytes), []):
lines.sort(key=second_column) # sort current batch
f = TemporaryFile("w+")
f.writelines(lines)
f.seek(0) # rewind
sorted_files.append(f)# merge & write the resultsys.stdout.writelines(merge(*sorted_files, key=second_column))# clean upfor f in sorted_files:
f.close() # temporary file is deleted when it closesiters = [((second_column(line), line) for line in file)
for file in sorted_files] # note: this makes the sort unstablesorted_lines = (line for _, line in merge(*iters))sys.stdout.writelines(sorted_lines)
用法:$ python sort-k2-n.py < input.txt > output.txt
最后
以上就是斯文火为你收集整理的python 文件排序_使用Python对文本文件进行排序的全部内容,希望文章能够帮你解决python 文件排序_使用Python对文本文件进行排序所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复