python利用多种方式来统计词频(单词个数)

yipeiwu_com6年前Python基础

python的思维就是让我们用尽可能少的代码来解决问题。对于词频的统计,就代码层面而言,实现的方式也是有很多种的。之所以单独谈到统计词频这个问题,是因为它在统计和数据挖掘方面经常会用到,尤其是处理分类问题上。故在此做个简单的记录。

统计的材料如下:

document = [
  'look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes',
 'the', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not', 'around', 'the',
 'eyes', "don't", 'look', 'around', 'the', 'eyes', 'look', 'into',
 'my', 'eyes', "you're", 'under']

直接使用dict来进行统计(遍历+循环)

word_count = {}
for word in document:
  if word in word_count:
    word_count[word] += 1
 else:
    word_count[word] = 1

更优雅的实现方式

#假如字典中不存在给定的键,则返回参数中提供的默认值;反之,则返回字典中保存的值。
for word in document:
  previous_count = word_count.get(word, 0)
  word_count[word] = previous_count + 1
#可以合并成一行
for word in document:
 word_count[word] = word_count.setdefault(word, 0) + 1

使用defalutdict来实现

# 使用collections中的defalutdict来实现,defalutdict是一种值可以默认设置的dict
from collections import defaultdict
word_count = defaultdict(int)
for word in document:
  word_count[word] += 1

使用Counter

word_counter = Counter(document)

Counter既然是一个计数器,那么它本身也就具有很多统计的方法。例如,最常见的词频统计的排序,可以获得前n个最高的词频。

# 返回前n个最高词频,以字典的形式
word_counter.most_common(n)

显然,使用defalutdict和Counter代码最简洁,更能符合python开发之道。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python中关于时间和日期函数的常用计算总结(time和datatime)

1.获取当前时间的两种方法: 复制代码 代码如下:import datetime,timenow = time.strftime("%Y-%m-%d %H:%M:%S")print no...

Python使用sorted对字典的key或value排序

sorted函数 sorted(iterable,key,reverse) iterable 待排序的可迭代对象 key 对应的是个函数, 该函数用来决定选取用哪些值来进行排...

PyCharm设置SSH远程调试的方法

PyCharm设置SSH远程调试的方法

一、环境 系统环境:windows10 64位 软件:PyCharm2017.3 本地Python环境:Python2.7 二、配置 2.1配置远程调试 第一步:运行PyCharm,然后...

详细介绍Python进度条tqdm的使用

详细介绍Python进度条tqdm的使用

前言 有时候在使用Python处理比较耗时操作的时候,为了便于观察处理进度,这时候就需要通过进度条将处理情况进行可视化展示,以便我们能够及时了解情况。这对于第三方库非常丰富的Python...

如何利用Boost.Python实现Python C/C++混合编程详解

前言 学习中如果碰到问题,参考官网例子: D:\boost_1_61_0\libs\python\test 参考:Boost.Python 中英文文档。 利用Boost.Python...