2024-04-27 04:30:47 发布
网友
python是否有类似于linux命令的命令:
cat file.txt | sort -n | uniq -c
其中,它对每一新行上的整数文本文件进行排序和计算频率,并将以以下形式输出:
如果没有,我可以简单地os.system(cat file.txt | sort -n | uniq -c)?在
os.system(cat file.txt | sort -n | uniq -c)
您可以使用itertools.groupby
itertools.groupby
from itertools import groupby words = ['blah', 'blah2'] my_result = dict((key, len(list(word_group))) for key, word_group in groupby(sorted(words)))
试试collections.Counter
>>> import collections >>> collections.Counter(['asdf', 'sdfg', 'asdf', 'qwer', 'sdfg', 'asdf']) Counter({'asdf': 3, 'sdfg': 2, 'qwer': 1}) >>> collections.Counter(map(str.strip, open('file.txt').readlines())) Counter({'spam': 5, 'hello': 3, 'world': 2, 'eggs': 2})
import collections c = collections.Counter() with open('file.txt') as f: for text in f: c.update( [int(text.strip())] ) c_sorted = sorted(c.most_common()) for key, val in c_sorted: print val, key
您可以使用
itertools.groupby
试试collections.Counter
相关问题 更多 >
编程相关推荐