Python实现的统计文章单词次数功能示例

作者:_梧桐雨 时间:2022-03-15 11:38:07 

本文实例讲述了Python实现的统计文章单词次数功能。分享给大家供大家参考,具体如下:

题目是这样的:你有一个目录,放了你一个月的日记,都是 txt,为了避免分词的问题,假设内容都是英文,请统计出你认为每篇日记最重要的词。

其实就是统计一篇文章出现最多的单词,但是要去除那些常见的连词、介词和谓语动词等,代码:


#coding=utf-8
import collections
import re
import os
useless_words=('the','a','an','and','by','of','in','on','is','to')
def get_important_word(file):
 f=open(file)
 word_counter=collections.Counter()
 for line in f:
   words=re.findall('\w+',line.lower())
   word_counter.update(words)
 f.close()
 most_important_word=word_counter.most_common(1)[0][0]
 count=2
 while(most_important_word in useless_words):
   most_important_word=word_counter.most_common(count)[count-1][0]
   count+=1
 num=word_counter.most_common(count)[count-1][1]
 print 'the most important word in %s is %s,it appears %d times'%(file,most_important_word,num)
if __name__=='__main__':
 filepath='.'
 for dirpath,dirname,dirfiles in os.walk(filepath):
   for file in dirfiles:
     if os.path.splitext(file)[1]=='.txt':
       abspath=os.path.join(dirpath,file)
       if os.path.isfile(abspath):
         get_important_word(abspath)

学习笔记:

collections模块,是python内建的模块,提供了许多有用的集合类。我们这里用到了Counter类和其中的most_common()方法

PS:这里再为大家推荐2款相关统计工具供大家参考:

在线字数统计工具:
http://tools.jb51.net/code/zishutongji

在线字符统计与编辑工具:
http://tools.jb51.net/code/char_tongji

希望本文所述对大家Python程序设计有所帮助。

来源:https://blog.csdn.net/qq_20817327/article/details/77655399

标签:Python,统计,单词次数
0
投稿

猜你喜欢

  • 设计原则-控件Balloons(气球状提示)

    2009-08-15 12:34:00
  • oracle执行cmd的实现方法

    2009-04-24 12:10:00
  • 微信小程序开发实例详解

    2022-11-07 19:55:48
  • SQL和Oracle对数据库事务处理的差异性

    2009-10-14 09:43:00
  • 整理Python中的赋值运算符

    2021-10-30 16:25:21
  • 多阶段构建优化Go 程序Docker镜像

    2024-02-20 13:57:40
  • Python Pandas处理CSV文件的常用技巧分享

    2022-06-18 12:56:19
  • Django实现将views.py中的数据传递到前端html页面,并展示

    2022-04-04 10:44:56
  • vue $mount 和 el的区别说明

    2024-04-28 09:20:24
  • 如何给Python代码进行加密

    2021-08-24 16:24:30
  • 简单了解django索引的相关知识

    2021-10-01 14:55:43
  • 详解Python图像处理库Pillow常用使用方法

    2022-07-17 11:04:53
  • Oracle关于时间/日期的操作

    2024-01-21 23:39:42
  • python解析xml文件实例分享

    2021-11-20 07:56:14
  • Python中字典和JSON互转操作实例

    2023-03-12 14:18:11
  • Sublime Text 配置 Python 环境的问题及解决方案

    2022-04-26 15:14:41
  • 通过遮罩层实现浮层DIV登录的js代码

    2024-06-24 00:08:58
  • show一下刚做的系统登录界面

    2008-09-13 19:13:00
  • python lxml中etree的简单应用

    2022-01-11 09:34:15
  • keras CNN卷积核可视化,热度图教程

    2021-03-15 05:06:15
  • asp之家 网络编程 m.aspxhome.com