python统计单词出现次数


本文摘自php中文网,作者angryTom,侵删。

python统计单词出现次数

做单词词频统计,用字典无疑是最合适的数据类型,单词作为字典的key, 单词出现的次数作为字典的 value,很方便地就记录好了每个单词的频率,字典很像我们的电话本,每个名字关联一个电话号码。

下面是具体的实现代码,实现了从importthis.txt文件读取单词,并统计出现次数最多的5个单词。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

# -*- coding:utf-8 -*-

import io

import re

 

class Counter:

    def __init__(self, path):

        """

        :param path: 文件路径

        """

        self.mapping = dict()

        with io.open(path, encoding="utf-8") as f:

            data = f.read()

            words = [s.lower() for s in re.findall("\w+", data)]

            for word in words:

                self.mapping[word] = self.mapping.get(word, 0) + 1

 

    def most_common(self, n):

        assert n > 0, "n should be large than 0"

        return sorted(self.mapping.items(), key=lambda item: item[1], reverse=True)[:n]

 

if __name__ == '__main__':

    most_common_5 = Counter("importthis.txt").most_common(5)

    for item in most_common_5:

        print(item)

执行效果:

阅读剩余部分

相关阅读 >>

Python temp是什么

Python 文件定位是什么?文件定位有什么作用?

Python怎么截图

Python 怎么用for重复(循环)

Python如何赚外快

Python函数式编程的详细分析(代码示例)

深入理解上篇之 Python的进程和线程

Python怎么读取文件内容

Python数据结构:一个被低估的namedtuple(二)

Python画星空源代码是什么?

更多相关阅读请进入《Python》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...