欢迎来到代码驿站!

Python代码

当前位置:首页 > 软件编程 > Python代码

python统计文章中单词出现次数实例

时间:2021-09-15 10:44:49|栏目: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)

知识点补充

1、如何正确读写文件

2、如何对数据进行排序

3、字典数据类型的运用

4、正则表达式的运用

上一篇:python爬取之json、pickle与shelve库的深入讲解

栏    目:Python代码

下一篇:使用gunicorn部署django项目的问题

本文标题:python统计文章中单词出现次数实例

本文地址:http://www.codeinn.net/misctech/175269.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有