作业要求参见:https://edu.cnblogs.com/campus/nenu/2018fall/homework/2126
作业代码地址:https://git.coding.net/onion102983/cipintongji.git 代码为wf.py文件用python语言编码
用f = open(path, encoding=‘utf-8‘)接收文件路径并传入
利用read()读取文本内容,lower()把所有大写单词转化为小写单词
通过正则表达式用re.findall()生成列表
用collections.Counter对象统计单词的计数并用most_common(n)方法返回计数值最大的n个元素的元组列表
利用Pyinstaller和Pywin32执行命令Pyinstaller.py -f wf.py将Python脚本(.py)转换为可执行文件(.exe)
1 f = open(path, encoding=‘utf-8‘) 2 words = re.findall(r‘\w+‘, f.read().lower()) 3 collect = collections.Counter(words) 4 num = 0 5 for i in collect: 6 num += 1 7 print(‘total %d words\n‘ % num) 8 result = collect.most_common(10) 9 for j in result: 10 print(‘%-8s%5d‘ % (j[0], j[1]))
利用参数sys.argv[1] 是否等于 ‘-s‘来判断执行功能一还是功能二
如果命令行参数带有‘-s‘的传入sys.argv[2] 作为open的路径参数不带的则传入sys.argv[1] 并且拼入字符串‘.txt‘作为参数
1 if sys.argv[1] == ‘-s‘: 2 doCount(sys.argv[2]) 3 else: 4 doCount(sys.argv[1]) 5 6 7 s = ‘.txt‘ 8 if s in accept: 9 path = accept 10 else: 11 path = accept + ‘.txt‘
用os.path.isdir()判断是否为文件夹利用for循环遍历里面文件
用os.path.isfile()判断是否为文件在调用定义好的词频统计函数进行输出
1 elif os.path.isdir(sys.argv[1]): 2 fileFindAndCount(sys.argv[1]) 3 4 5 def fileFindAndCount(path1): 6 files = os.listdir(path1) 7 for file in files: 8 if os.path.isfile(file): 9 doSomeFileCount(file)
原文:https://www.cnblogs.com/nenusoft/p/9696784.html