python统计单词出现次数-Python教程

资源魔 18 0

python统计单词呈现次数

做单词词频统计,用字典无疑是最合适的数据类型,单词作为字典的key, 单词呈现的次数作为字典的 value,很不便地就记载好了每一个单词的频次,字典很像咱们的德律风本,每一个名字联系关系一个德律风号码。

上面是详细的完成代码,完成了从importthis.txt文件读取单词,并统计呈现次数最多的5个单词。

# -*- 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_co妹妹on(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_co妹妹on_5 = Counter("importthis.txt").most_co妹妹on(5)
    for item in most_co妹妹on_5:
        print(item)

执行成果:

('is', 10)
('better', 8)
('than', 8)
('the', 6)
('to', 5)

更多python教程,保举学习:Python视频教程

以上就是python统计单词呈现次数的具体内容,更多请存眷资源魔其它相干文章!

标签: Python python教程 python编程 python使用问题 统计单词

抱歉,评论功能暂时关闭!