本文實例講述了Python實現的統(tǒng)計文章單詞次數功能。分享給大家供大家參考,具體如下:
題目是這樣的:你有一個目錄,放了你一個月的日記,都是 txt,為了避免分詞的問題,假設內容都是英文,請統(tǒng)計出你認為每篇日記最重要的詞。
其實就是統(tǒng)計一篇文章出現最多的單詞,但是要去除那些常見的連詞、介詞和謂語動詞等,代碼:
#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款相關統(tǒng)計工具供大家參考:
在線字數統(tǒng)計工具:
http://tools.jb51.net/code/zishutongji
在線字符統(tǒng)計與編輯工具:
http://tools.jb51.net/code/char_tongji
更多關于Python相關內容感興趣的讀者可查看本站專題:《Python文件與目錄操作技巧匯總》、《Python文本文件操作技巧匯總》、《Python數據結構與算法教程》、《Python函數使用技巧總結》、《Python字符串操作技巧匯總》及《Python入門與進階經典教程》
希望本文所述對大家Python程序設計有所幫助。
更多文章、技術交流、商務合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯(lián)系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
