python统计文章单词次数
来源:互联网 发布:淘宝女式长袖衬衣 编辑:程序博客网 时间:2024/06/05 04:45
题目是这样的:你有一个目录,放了你一个月的日记,都是 txt,为了避免分词的问题,假设内容都是英文,请统计出你认为每篇日记最重要的词。
其实就是统计一篇文章出现最多的单词,但是要去除那些常见的连词、介词和谓语动词等,代码:
#coding=utf-8import collectionsimport reimport osuseless_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)
学习笔记:
1、collections模块,是python内建的模块,提供了许多有用的集合类。我们这里用到了Counter类和其中的most_common()方法
阅读全文
0 0
- python统计文章单词次数
- 统计文章中单词出现的次数
- 统计英文文章中单词出现次数
- 统计文章中单词出现的次数
- 输入文章,统计各个单词出现次数
- python 统计文章单词个数
- python统计文本中单词出现次数
- 统计文章中单词出现的次数(续)
- java统计一篇文章中单词出现的次数
- 统计文章内各个单词出现的次数
- 统计文章内各个单词出现的次数 (STL)
- java统计一篇文章中单词出现的次数
- 统计一篇文章中每个单词出现的次数
- java统计文章中单词出现的次数
- java 统计文章中每个单词出现的次数
- Python 统计文章单词出现频率
- 统计单词次数
- 统计单词出现次数
- [js高手之路]使用原型对象(prototype)需要注意的地方
- Spring通过注解配置bean
- caffe: 新建一个loss层
- 未知:六边形——题解
- tp5--权限操作(auth类)基本使用
- python统计文章单词次数
- ImageIo类
- hdoj 1695 GCD
- 启动Tomcat失败,错误提示:the JRE_HOME environment variable is not defined correctly
- java String方法摘要详解
- redis expire key 过期不删除
- writing-mode属性
- 宏定义求数组元素个数
- 数据结构--左偏树(可并堆)