python统计单词出现次数

python统计单词出现次数,第1张

概述python统计单词出现次数

python统计单词出现次数

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

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

# -*- Coding:utf-8 -*-import ioimport reclass 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统计单词出现次数所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/langs/1184187.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-03
下一篇2022-06-03

发表评论

登录后才能评论

评论列表(0条)

    保存