【问题标题】:Python similar uniq -c command?Python 类似 uniq -c 命令?
【发布时间】:2014-06-24 17:31:34
【问题描述】:

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) 吗?

【问题讨论】:

  • collections.Counter() - 不完全是uniq -c,但非常方便。

标签: python linux sorting uniq


【解决方案1】:
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

【讨论】:

  • 这似乎只输出数字 0 - 9
  • 您没有添加file.txt 来测试它。显示一些输入数据。
  • 我发现了问题——我忘了​​在update()中使用[]
【解决方案2】:

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

【讨论】:

    【解决方案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)))
    

    【讨论】:

      【解决方案4】:

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

      可能值得考虑,但 return_counts 选项在旧版本的库中不可用,因此取决于您可以使用什么。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-01-05
        • 1970-01-01
        • 1970-01-01
        • 2012-04-24
        • 1970-01-01
        • 2023-04-02
        • 1970-01-01
        相关资源
        最近更新 更多