# !/usr/bin/env python # -*- coding:utf-8 -*- """ 實現指定目錄下的文件單詞計數統計: 例如:你輸入 nginx.conf(將要統計的文件)--->/usr(nginx.conf的搜索目錄)--->輸入要得到該文件的前top個單詞數目 結果: 得到 ---> (單詞名,該文件的中該單詞出現的次數) """ import os import sys import re def getfiles(): file_name = raw_input("please enter the file_name you want count the file\n") path = raw_input("please enter the root path : example: /tmp\n") if not os.path.exists(path): print "sorry,the path %s is not exists !!" %(path) sys.exit(1) else: cmd = "find " + path + " -name "+ file_name print cmd files = os.popen(cmd).readlines() files1 = [file[:-1] for file in files] return files1 def countword(top_num): files = getfiles() for file in files: with open(file) as f: # get the file content and strip the space and line break(acording the os.linesep) file_content = f.read().replace(os.linesep,"").replace("#","").replace("/","").replace(";","").replace("}","").replace("{","") file_words = file_content.split(" ") wordcounts = [(word, file_words.count(word)) for word in file_words] # get uniq wordcounts wordcounts = list(set(wordcounts)) # get the max wordcounts # wordcounts = [wordc for wordc in wordcounts if re.match("^/s*",wordc[0])] wordcounts = sorted(wordcounts,key=lambda d: d[1], reverse=True) # get the right word format wordcounts = [wordcount for wordcount in wordcounts if re.match("\w",wordcount[0])] if len(wordcounts[:int(top_num)]) > 0: print "文件:" + f.name + "的前" + top_num + "個單詞是及個數分別是:\n" + str(wordcounts[:int(top_num)]) else: print "文件:" + f.name + "是個空文件!!\n" + str(wordcounts[:int(top_num)]) if __name__ == "__main__": top_num = raw_input("請輸入要得到統計單詞數目的前多少個\n") countword(top_num)
python實現linux下指定目錄下文件中的單詞個數統計
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.