python统计单词出现次数

发布时间:2022-05-15 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了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统计单词出现次数所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签:python