Python强化训练笔记(三)——词频的统计

现有列表如下:

[6, 7, 5, 9, 4, 1, 8, 6, 2, 9]

希望统计各个元素出现的次数,可以看作一个词频统计的问题。

我们希望最终得到一个这样的结果:{6:2, 7:1...}即 {某个元素:出现的次数...}

首先要将这些元素作为字典的键,建立一个初值为空的字典:

>>> from random import randint
>>> l = [randint(1,10) for x in xrange(10)]
>>> l
[6, 7, 5, 9, 4, 1, 8, 6, 2, 9]
>>> d = dict.fromkeys(l, 0)
>>> d
{1: 0, 2: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0}
# 现在的任务是需要将d中每个键所对应的值统计出来
>>> for x in l:
>>>     d[x] += 1
>>> d
{1: 1, 2: 1, 4: 1, 5: 1, 6: 2, 7: 1, 8: 1, 9: 2}
# 这就统计完了所有的元素出现的次数

另外一种方法,利用collections模块中的Counter对象

>>> from collections import Counter
# 这个Counter可以直接接受一个列表,将它转化为统计完成的结果
>>> d = Counter(l)
>>> d
Counter({6: 2, 9: 2, 1: 1, 2: 1, 4: 1, 5: 1, 7: 1, 8: 1})
# 该Counter对象是字典对象的子类,也可以通过键来访问对应值
>>> d[6]
2
# Counter对象方便之处在于它内置有most_common(n)方法,可以直接统计出前n个最高词频
>>> d.most_common(2)
[(6, 2), (9, 2)]

下面进行实践,对某篇文章进行词频统计,得到词频最高的十个词。

>>> import re
>>> from collections import Counter
>>> txt = open('CodingStyle.txt').read()
>>> new_txt = re.split('W+', txt)
>>> result = Counter(new_txt)
>>> result.most_common(10)
原文地址:https://www.cnblogs.com/shiyu404/p/5942213.html