小编给大家分享一下如何使用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()
方法
以上是“如何使用Python实现的统计文章单词次数功能”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。