一、程序分析
def process_file(dst): # 读文件到缓冲区
try: # 打开文件
f=open(dst,‘r‘)
except IOError as s:
print (s)
return None
try: # 读文件到缓冲区
x=f.read()
except:
print ("Read File Error!")
return None
bvffer=x
return bvffer
def process_buffer(bvffer):
if bvffer:
word_freq = {} #新建一个空字典word_freq
# 下面添加处理缓冲区 bvffer代码,统计每个单词的频率,存放在字典word_freq
for word in bvffer.split(): #.split()函数将bvffer切片
if word not in word_freq:
word_freq[word]=0
word_freq[word]+=1
return word_freq
def output_result(word_freq): #输出函数
if word_freq:
sorted_word_freq = sorted(word_freq.items(), key=lambda v: v[1], reverse=True)
for item in sorted_word_freq[:10]: # 输出 Top 10 的单词
print(item)
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser()
parser.add_argument(‘dst‘)
args = parser.parse_args()
dst = args.dst
bvffer = process_file(dst)
word_freq = process_buffer(bvffer)
output_result(word_freq)
二、代码风格说明
if/for/while一定要换行
例如:
if bvffer:
word_freq = {}
三、程序运行命令、运行结果截图
四、性能分析结果及改进
执行时间最多的代码:
执行次数最多的代码:
原文:https://www.cnblogs.com/uiki007/p/9748035.html