详解Python用三种方式统计词频的方法

yipeiwu_com6年前Python基础

三种方法:

①直接使用dict

②使用defaultdict

③使用Counter

 ps:`int()`函数默认返回0

 ①dict

text = "I'm a hand some boy!"
frequency = {}
for word in text.split():
  if word not in frequency:
    frequency[word] = 1
  else:
    frequency[word] += 1

 ②defaultdict

import collections
frequency = collections.defaultdict(int)
text = "I'm a hand some boy!"
for word in text.split():
  frequency[word] += 1

 ③Counter

import collections
text = "I'm a hand some boy!"
frequency = collections.Counter(text.split())

总结

以上所述是小编给大家介绍的Python用三种方式统计词频的方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对【听图阁-专注于Python设计】网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

相关文章

Python网络编程中urllib2模块的用法总结

Python网络编程中urllib2模块的用法总结

一、最基础的应用 import urllib2 url = r'http://www.baidu.com' html = urllib2.urlopen(url).read()...

python 统计数组中元素出现次数并进行排序的实例

如下所示: lis = [12,34,456,12,34,66,223,12,5,66,12,23,66,12,66,5,456,12,66,34,5,34] def test1(...

python3.5安装python3-tk详解

python3.5安装python3-tk详解

 在python3.5下安装好matplotlib后,准备显示一张图片测试一下,但是控制台报错说需要安装python3-tk,我天真的以为直接: sudo apt-get i...

python多线程与多进程及其区别详解

前言 个人一直觉得对学习任何知识而言,概念是相当重要的。掌握了概念和原理,细节可以留给实践去推敲。掌握的关键在于理解,通过具体的实例和实际操作来感性的体会概念和原理可以起到很好的效果。本...

python中csv文件的若干读写方法小结

如下所示: //用普通文本文件方式打开和操作 with open("'file.csv'") as cf: lines=cf.readlines() .........