python统计出现频率最高的单词_Python菜谱10:统计单词出现的频率

平时我们在工作的时候需要统计一篇文章或者网页出现频率最高的单词,或者需要统计单词出现频率排序。那么如何完成这个任务了?

例如,我们输入的语句是 “Hello there this is a test. Hello there this was a test, but now it is not.”,希望得到的升序的结果:

[[1, 'but'], [1, 'it'], [1, 'not.'], [1, 'now'], [1, 'test,'], [1, 'test.'], [1, 'was'], [2, 'Hello'], [2, 'a'], [2, 'is'], [2, 'there'], [2, 'this']]

得到降序的结果是:

[[2, 'this'], [2, 'there'], [2, 'is'], [2, 'a'], [2, 'Hello'], [1, 'was'], [1, 'test.'], [1, 'test,'], [1, 'now'], [1, 'not.'], [1, 'it'], [1, 'but']]

完成这个结果的代码如下:

class Counter(object):

def __init__(self):

self.dict = {}

def add(self, item):

count = self.dict.setdefault(item, 0)

self.dict[item] = count + 1

def counts(self, desc=None):

result = [[val, key] for (key, val) in self.dict.items()]

result.sort()

if desc:

result.reverse()

return result

if __name__ == '__main__':

'''Produces:

>>> Ascending count:

[[1, 'but'], [1, 'it'], [1, 'not.'], [1, 'now'], [1, 'test,'], [1, 'test.'], [1, 'was'], [2, 'Hello'], [2, 'a'], [2, 'is'], [2, 'there'], [2, 'this']]

Descending count:

[[2, 'this'], [2, 'there'], [2, 'is'], [2, 'a'], [2, 'Hello'], [1, 'was'], [1, 'test.'], [1, 'test,'], [1, 'now'], [1, 'not.'], [1, 'it'], [1, 'but']]

'''

sentence = "Hello there this is a test. Hello there this was a test, but now it is not."

words = sentence.split()

c = Counter()

for word in words:

c.add(word)

print "Ascending count:"

print c.counts()

print "Descending count:"

print c.counts(1)

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值