005_004 Python 统计值 并按照次数排序 可以通过字典的值对key进行排序

本文介绍了一种使用Python实现的统计文本中单词出现频率的方法,并展示了如何按频率对单词进行升序和降序排序。此外,还提供了一个利用内置函数进行排序的例子。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

代码如下:

#encoding=utf-8

print '中国'

#统计值 并按照次数排序 可以通过字典的值对key进行排序

#通过字典来实现
class hist(dict):
    def add(self,item,increment=1):
        self[item]=increment + self.get(item,0)

    def counts(self,reverse=False):
        aux=[(self[k],k) for k in self]
        aux.sort(cmp=None, key=None, reverse=False)
        if reverse:
            aux.reverse()
        return [k for v,k in aux]

hist1=hist()
hist1.add(3)
hist1.add(3)
hist1.add(1)

print hist1.counts()

#通过list来实现
class histlist(list):
    def __init__(self,n):
        list.__init__(self,n*[0])
    def add(self,item,increment=1):
        self[item] += increment
    def counts(self,reverse=False):
        aux=[(v,k) for k,v in enumerate(self)]
        aux.sort(cmp=None, key=None, reverse=False)
        if reverse:aux.reverse()
        return [k for v,k in aux]
    
hist1=histlist(4)
hist1.add(3)
hist1.add(3)
hist1.add(1)

print hist1


sentence = ''' Hello there this is a test.  Hello there this was a test,
           but now it is not. '''
words = sentence.split( )
c = hist( )
for word in words: c.add(word)
print "Ascending count:"
print c.counts( )
print "Descending count:"
print c.counts(reverse=True)

from operator import itemgetter

#itemgetter为获取当前维度的值 (key,val) val为维度一 排序当前维度的值
def dict_items_sorted_by_value(d, reverse=False):
    return sorted(d.iteritems( ), key=itemgetter(1), reverse=reverse)

print dict_items_sorted_by_value(c)
打印结果如下:

中国
[1, 3]
[0, 1, 0, 2]
Ascending count:
['but', 'it', 'not.', 'now', 'test,', 'test.', 'was', 'Hello', 'a', 'is', 'there', 'this']
Descending count:
['this', 'there', 'is', 'a', 'Hello', 'was', 'test.', 'test,', 'now', 'not.', 'it', 'but']
[('not.', 1), ('it', 1), ('but', 1), ('test,', 1), ('now', 1), ('was', 1), ('test.', 1), ('a', 2), ('this', 2), ('is', 2), ('there', 2), ('Hello', 2)]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

书山登峰人

精品不易

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值