Python使用collections模块统计单词频率(出现次数)

3 篇文章 0 订阅

1.collections模块

在内置数据类型(dict、list、set、tuple)的基础上,collections模块还提供了几个额外的数据类型:Counter、deque、defaultdict、namedtuple等。

1.1 Counter

计数器,主要用来记录每一个元素出现的次数

可以用来统计单词出现的次数

import collections

# 统计text_list中单词出现的次数
text_list = ['this', 'isn', 'to', 'be', 'out', 'that', 'has', 'in', 'the', 'past', 'the', 'didn', 'go', 'so', 'well', 'for', 'jobs', 'were', 'by', 'but', 'it', 'and', 'more', 'jobs', 'than', 'it', 'by', 'down', 'and', 'free', 'from', 'hard', 'work', 'but', 'in', 'the', 'term', 'may', 'need', 'lot', 'of', 'help', 'the', 'step', 'as', 'erik', 'and', 'in', 'the', 'age', 'be', 'and', 'job', 'from', 'to', 'to', 'less', 'on', 'and', 'more', 'on', 'and', 'do', 'job', 'of', 'and', 'work', 'can', 'the', 'kind', 'it', 'make', 'and', 'to', 'new', 'will', 'be', 'able', 'to', 'do', 'so', 'into', 'debt', 'the', 'of', 'with', 'the', 'need', 'for', 'the', 'to', 'its', 'new', 'must', 'be', 'made', 'in', 'eras', 'of', 'the', 'by', 'up', 'ways', 'to', 'and', 'the', 'best', 'uses', 'of', 'and', 'been', 'yet', 'the', 'the', 'new', 'that', 'will', 'them', 'to', 'the', 'gap', 'and', 'and', 'the', 'net', 'will', 'have', 'to', 'be', 'on', 'low', 'wage', 'need', 'to', 'be', 'cut', 'and', 'wage', 'such', 'as', 'the', 'tax', 'be', 'this', 'work', 'for', 'job', 'and']

# 词频统计
words_frequency = collections.Counter(text_list).most_common()

print(words_frequency)

输出:

在这里插入图片描述

1.2 namedtuple

生成可以使用名字来访问元素内容的tuple

from collections import namedtuple

Point = namedtuple('Point',['x','y'])    #创建模板,namedtuple("名称",[属性list])
p = Point(1,2)    #传入内容

print(p.x)    # 输出 :1
print(p.y)    # 输出 :2

1.3 deque

双端队列,可以快速的在两端追加和推出对象

from collections import deque
 
q = duque(['a','b','c'])
q.append('x')
q.leftappend('1')    # 向列表的头部添加元素
q.pop()            # 弹出列表的尾部最后一个元素
q.leftpop()        # 弹出列表的头部第一个元素

print(q)

输出: [‘a’,‘b’,‘c’]

1.4 defalutdict

带有默认值的字典

作用:在使用dict时,如果引用的Key不存在,就会抛出KeyEroor,如果希望key不存在时,返回一个默认值,就可以使用defalutdict

from collections import defaultdict
 
dd = defaultdict(lambda: 'N/A')
dd['key1'] = 'abc'
 
print(dd['key1'])    # 键存在  输出: 'abc'
print(dd['key2'])    # 键不存在  输出:'N/A'
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值