Python词频统计 Posted on 2017-05-25 Edited on 2022-01-29 In python , foundation 12345678910111213141516171819202122232425262728293031323334#!/usr/bin/env python#coding:utf-8from random import randint""" 词的频次统计 统计重复的词的次数,用字典的形式展现"""data = [randint(0,10) for _ in xrange(0,20)]print data## 常规处理# 根据键生成一个字典,赋值0ddata = dict.fromkeys(data,0)print ddata# 迭代统计for x in data: ddata[x]+=1print ddata## 用collections 的counterfrom collections import Counterddata2 = Counter(data)# 统计最高的4位print ddata2.most_common(4) 输出: 12345[1, 0, 5, 6, 6, 4, 8, 7, 3, 1, 2, 10, 9, 5, 9, 3, 10, 9, 5, 4]{0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0}{0: 1, 1: 2, 2: 1, 3: 2, 4: 2, 5: 3, 6: 2, 7: 1, 8: 1, 9: 3, 10: 2}[(5, 3), (9, 3), (1, 2), (3, 2)]