Python类似uniqc命令?

2024-04-27 04:30:47 发布

您现在位置:Python中文网/ 问答频道 /正文

python是否有类似于linux命令的命令:

cat file.txt | sort -n | uniq -c

其中,它对每一新行上的整数文本文件进行排序和计算频率,并将以以下形式输出:

^{pr2}$

如果没有,我可以简单地os.system(cat file.txt | sort -n | uniq -c)?在


Tags: 命令txt排序oslinux整数sort形式
3条回答

您可以使用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

相关问题 更多 >