3333

学号 2017****1016
姓名 李双阳
码云地址 https://gitee.com/LSY_IT/events

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

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

def process_buffer(bvffer): (统计每个单词次数)
if bvffer:
word_freq = {}
# 下面添加处理缓冲区 bvffer代码,统计每个单词的频率,存放在字典word_freq
for item in bvffer.strip().split():
word = item.strip(punctuation+' ')
if word in word_freq.keys():
word_freq[word] += 1
else:
word_freq[word] = 1
return word_freq

def output_result(word_freq): (排序输出前10个次数单词)
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": (调用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)

性能分析结果及改进。
用命令python -m cProfile word_freq.py Gone_with_the_wind.txt运行

总共有3298次函数调用,程序总共耗时0.006秒

执行次数最多的代码

总结反思
学习了词频统计这个程序,使我了解了性能分析,了解python这门语言。。

posted @ 2019-04-08 14:31  L双阳  阅读(688)  评论(0编辑  收藏  举报