python实现linux下指定目录下文件中的单词个数统计
2016-08-13 00:34
816 查看
# !/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实现指定目录下批量文件的单词计数:串行版本
- python 实现统计ftp服务器指定目录下文件夹数目、文件数目及所有文件大小 本次主要为满足应用方核对上传到ftp服务器的文件是否缺漏。 主要要求:指定目录下,文件夹数目/文件数目/所有文件大小
- python实现指定目录下批量文件的单词计数:并发版本
- linux下用python统计某个目录下指定后缀文件的个数
- python实现指定目录下批量文件的单词计数:串行版本
- python实现指定目录下JAVA文件单词计数的多进程版本
- python实现指定目录下批量文件的单词计数:并发版本
- Linux下递归遍历指定目录下的文件内容并删除的函数实现
- Python实现查找指定目录下包括某关键字的所有文件脚本
- Python中实现从目录中过滤出指定文件类型的文件
- Python中实现从目录中过滤出指定文件类型的文件
- Python 实现在对一个目录下所有文件,指定某一行之后添加内容(批处理脚本)
- Python实现批量更换指定目录下文件扩展名的方法
- python统计指定目录内文件的代码行数
- Python 实现指定目录下 删除指定大小的文件
- C++实现Linux下遍历指定目录下的文件
- Python实现批量更换指定目录下文件扩展名的方法
- Python实现扫描指定目录下的子目录及文件的方法
- python实现在目录中查找指定文件的方法
- 利用Python 1分钟搭建测试Web服务器,可实现linux目录文件共享