词频统计

2017*****7039

于朗

 码云:https://gitee.com/canyinyyylll/word_frequency

2) 程序分析,对程序中的四个函数做简要说明。要求附上每一段代码及对应的说明。

1.

def process_file(dst): 
try: # 打开文件
txt=open(dst,"r")
except IOError as s:
print (s)
return None
try: # 读文件到缓冲区
bvffer=txt.read()
except:
print ("Read File Error!")
return None
txt.close()
return bvffer

 

 

2.

# 统计每个单词的频率,存放在字典word_freq
def process_buffer(bvffer):
if bvffer:
word_freq = {}
bvffer=bvffer.lower()
for x in '~!@#$%^&*()_+/*-+\][':
bvffer=bvffer.replace(x, " ")
words=bvffer.strip().split()
for word in words:
word_freq[word]=word_freq.get(word,0)+1
return word_freq

 

3

.# 输出 Top 10 的单词
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]: 
print (item)

 

4.

if __name__ == "__main__":
import cProfile
import pstats
cProfile.run("main()", "result")
# 直接把分析结果打印到控制台
p = pstats.Stats("result") # 创建Stats对象
p.strip_dirs().sort_stats("call").print_stats() # 按照调用的次数排序
p.strip_dirs().sort_stats("cumulative").print_stats() # 按执行时间次数排序
p.print_callers(0.5, "process_file") # 有哪些函数调用了process_file,小数,表示前百分之几的函数信息
p.print_callers(0.5, "process_buffer") # 有哪些函数调用了process_buffer
p.print_callers(0.5, "output_result") # 有哪些函数调用了output_res

 

3) 性能分析结果及改进。

  • 指出执行次数最多的代码,执行时间最长的代码。
  • 给出改进优化的方法以及你的改进代码

 

4) 程序运行命令、运行结果截图以及改进后的程序运行命令及结果截图 。

 

 

5) 给出你对此次任务的总结与反思。

学到了很多

posted @ 2019-03-27 19:31  残音  阅读(129)  评论(0编辑  收藏  举报