教程集 www.jiaochengji.com
教程集 >  脚本编程  >  php  >  正文 python统计单词出现次数

python统计单词出现次数

发布时间:2020-10-04   编辑:jiaochengji.com
教程集为您提供python统计单词出现次数等资源,欢迎您收藏本站,我们将为您提供最新的python统计单词出现次数资源

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_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)

执行效果:

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

更多python教程,推荐学习:Python视频教程

以上就是python统计单词出现次数的详细内容,更多请关注教程集其它相关文章!

  • 本文原创发布教程集,转载请注明出处,感谢您的尊重!
  • 您可能感兴趣的文章:
    python统计单词出现次数
    Python中文分词的原理你知道吗?
    Python之jieba分词相关介绍
    PHP统计字符串中单词出现次数的函数
    seo搜索引擎关键词技术
    php 统计字数(支持中英文)的实现代码
    PHP中TF-IDF与余弦相似性计算文章相似性
    Python3爬虫进阶:中文分词(原理、工具)
    如何正确选择关键字
    awk统计文件中某关键词出现的次数

    [关闭]
    ~ ~