Python 中类似 uniq -c 的命令?

2 投票
4 回答
2325 浏览
提问于 2025-04-18 10:55

Python有没有类似于Linux命令的指令:

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

这个命令可以对一个文本文件进行排序,并计算每一行中整数出现的频率,最后输出的结果是这样的:

76539  1 
100441 2 
108637 3 
108874 4 
103580 5 
 91869 6 
 78458 7 
 61955 8 
 46100 9 
 32701 10 
 21111 11 
 13577 12 
  7747 13 
  4455 14 
  2309 15 
  1192 16 
   554 17 
   264 18 
   134 19 
    63 20 
    28 21 
    15 22 
    12 23 
     7 24 
     5 25

如果没有的话,我能不能简单地用 os.system(cat file.txt | sort -n | uniq -c) 这个命令呢?

4 个回答

0

https://docs.scipy.org/doc/numpy/reference/generated/numpy.unique.html

这个功能可能值得考虑,不过return_counts这个选项在旧版本的库里是没有的,所以要看你用的是什么版本。

0

你可以使用 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)))
1

试试 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})
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

撰写回答