黑松山资源网 Design By www.paidiu.com
本文实例讲述了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相关内容感兴趣的读者可查看本站专题:《Python文件与目录操作技巧汇总》、《Python文本文件操作技巧汇总》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程》
希望本文所述对大家Python程序设计有所帮助。
黑松山资源网 Design By www.paidiu.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
黑松山资源网 Design By www.paidiu.com
暂无评论...
更新日志
2024年10月07日
2024年10月07日
- 群星《前途海量 电影原声专辑》[FLAC/分轨][227.78MB]
- 张信哲.1992-知道新曲与精丫巨石】【WAV+CUE】
- 王翠玲.1995-ANGEL【新艺宝】【WAV+CUE】
- 景冈山.1996-我的眼里只有你【大地唱片】【WAV+CUE】
- 群星《八戒 电影原声带》[320K/MP3][188.97MB]
- 群星《我的阿勒泰 影视原声带》[320K/MP3][139.47MB]
- 纪钧瀚《胎教古典音乐 钢琴与大提琴的沉浸时光》[320K/MP3][148.91MB]
- 刘雅丽.2001-丽花皇后·EMI精选王【EMI百代】【FLAC分轨】
- 齐秦.1994-黄金十年1981-1990CHINA.TOUR.LIVE精丫上华】【WAV+CUE】
- 群星.2008-本色·百代音乐人创作专辑【EMI百代】【WAV+CUE】
- 群星.2001-同步过冬AVCD【环球】【WAV+CUE】
- 群星.2020-同步过冬2020冀待晴空【环球】【WAV+CUE】
- 沈雁.1986-四季(2012梦田复刻版)【白云唱片】【WAV+CUE】
- 纪钧瀚《胎教古典音乐 钢琴与大提琴的沉浸时光》[FLAC/分轨][257.88MB]
- 《国语老歌 怀旧篇 3CD》[WAV/分轨][1.6GB]