Python 50问 [3]:如何统计序列中元素的出现频度

常规解法:迭代

该问题的实际场景主要有两种,一是单纯的统计序列中元素的出现的次数,二是统计某篇文章中出现频度最高的英语单词等。

# 首先先来使用列表解析创建一个随机的序列
from random import randint

# 生成一个含有30个元素范围为0-20的随机序列
data = [randint(0, 20) for _ in xrange(30)]

# 统计结果是一个字典,其中data中的元素为键,0为初始值
c = dict.fromkeys(data, 0)

# 迭代
for x in data:
  c[x] += 1

print c

如此一来,就得到了序列中每个元素的出现次数。如果实际需求是找频度最高的前几个元素,可以对字典进行排序。(详见1.1 在列表、字典、集合中根据条件筛选数据,这里不再赘述。)

可见,步骤虽然简单,但仍然是比较繁琐的。那么,有没有什么优雅的解决方案呢?

Python 中优雅的解决方案

使用 collections 下的 Counter 对象,具体步骤:

  • 将序列传入 Counter 的构造器,得到 Counter 对象是元素频度的字典。
  • Counter.most_common(n)方法得到频度最高的n个元素的列表。
from random import randint
from collections import Counter

data = [randint(0, 20) for _ in xrange(30)]

c2 = Counter(data)

# 获取所有元素的出现频度的字典
print c2

# 获取出现频度最高的3个元素
print c2.most_common(3) # 返回一个列表,如[(5,4),(10,3),(20,3)]

对英语文章进行词频统计

由于本人是考研党,所以这里,我直接使用了2015年考研英语1的第4篇阅读的文本为例,获取其出现频度最高的10个单词。

    Two years ago, Rupert Murdoch's daughter,Elisabeth, spoke of the "unsettling dearth of integrity across so many of our institutions" Integrity had collapsed, she argued, because of a collective acceptance that the only "sorting mechanism" in society should be profit and the market. But "it's us, human beings, we the people who create the society we want, not profit".

    Driving her point home, she continued: "It's increasingly apparent that the absence of purpose, of a moral language within government, media or business could become one of the most dangerous foals for capitalism and freedom." This same absence of moral purpose was wounding companies such as News International, shield thought, making it more likely that it would lose its way as it had with widespread illegal telephone hacking.

    As the hacking trial concludes-finding guilty ones-editor of the News of the World, Andy Coulson, for conspiring to hack phones, and finding his predecessor, Rebekah Brooks, innocent of the same charge-the winder issue of dearth of integrity still standstill, Journalists are known to have hacked the phones of up to 5500 people. This is hacking on an industrial scale, as was acknowledged by Glenn Mulcaire, the man hired by the News of the World in 2001 to be the point person for phone hacking. Others await trial. This long story still unfolds.

    In many respects, the dearth of moral purpose frames not only the fact of such widespread phone hacking but the terms on which the trial took place .One of the astonishing revelations was how little Rebekah Brooks knew of what went on in her newsroom, wow little she thought to ask and the fact that she never inquired wow the stories arrived. The core of her successful defence was that she knew nothing.

    In today's world, title has become normal that well-paid executives should not be accountable for what happens in the organizations that they run perhaps we should not be so surprised. For a generation, the collective doctrine has been that the sorting mechanism of society should be profit. The words that have mattered are efficiency, flexibility, shareholder value, business-friendly, wealth generation, sales, impact and, in newspapers, circulation. Words degraded to the margin have been justice fairness, tolerance, proportionality and accountability.

    The purpose of editing the News of the World was not to promote reader understanding to be fair in what was written or to betray any common humanity. It was to ruin lives in the quest for circulation and impact. Ms Brooks may or may not have had suspicions about how her journalists got their stories, but she asked no questions, gave no instructions-nor received traceable, recorded answers.

我已将上述文件传到七牛云中:http://airing.ursb.me/python/text.txt,因此待会的代码中直接使用urllib2读取网络文件。

from collections import Counter
import re
import urllib2

# 读取网络文件并赋值于 txt 中
req = urllib2.Request('http://airing.ursb.me/python/text.txt')
response = urllib2.urlopen(req)
txt = response.read()

# 使用正则表达式分割 txt 中的单词存于序列中
# 再使用 Counter 进行频度统计返回字典
c3 = Counter(re.split('\W+', txt))

print c3.most_common(10)

# 打印结果为:[('the', 31), ('of', 23), ('to', 10), ('that', 9), ('was', 7), ('and', 7), ('in', 7), ('not', 6), ('she', 6), ('be', 6)]

如此,便完成了一个简单的词频统计。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 206,214评论 6 481
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 88,307评论 2 382
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 152,543评论 0 341
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 55,221评论 1 279
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 64,224评论 5 371
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,007评论 1 284
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,313评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,956评论 0 259
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 43,441评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,925评论 2 323
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,018评论 1 333
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,685评论 4 322
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,234评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,240评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,464评论 1 261
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,467评论 2 352
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,762评论 2 345

推荐阅读更多精彩内容