温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2020-09-16 06:05:24 来源:脚本之家 阅读:217 作者:Sinte-Beuve 栏目:开发技术

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开发之道。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI