词频统计
一、编译环境
IDLE python3.7
python 版本:python-3.7.1rc1-amd64
二、程序分析
1、读文件到缓冲区
from string import punctuation def process_file(path): # 读文件到缓冲区 try: # 打开文件 str = open (path, "r")#path为文件目录 except IOError as s: print (s) return None try: # 读文件到缓冲区 bvffer = str.read() except: print("Read File Error!"+bvffer) return None str.close() return bvffer
2、处理缓冲区,返回存放每个单词频率的字典word_freq(process_buffer)bvffer)
def process_buffer(bvffer): if bvffer: word_freq = {} # 下面添加处理缓冲区 bvffer代码,统计每个单词的频率,存放在字典word_freq strl_ist = bvffer.replace('/n', '').lower().split(' ')#把换行都换为空 for str in strl_ist: word_freq[str] = word_freq.get(str, 0) + 1#给单词计数 return word_freq
3、按照单词的频数排序,输出前十的单(output_result(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("词:%-5s 频:%-4d " % (item[0], item[1]))
4、主函数输出前十结果
if __name__ == "__main__": path ='txt/Gone_with_the_wind.txt' bvffer = process_file(path) word_freq = process_buffer(bvffer) output_result(word_freq)
三、代码风格说明
1. python3与python2在print函数的使用区别:python3中,print函数要加上()如下:
print(s)
2.缩进
使用四个空格进行缩进
def process_buffer(bvffer):
if buffer:
word_freq={}
四、程序运行命令,运行结果截图
测试对象:《Gone_with_the_wind》

五、性能分析及结果改进
5.1 总运行时间:

5.2 执行次数最多的部分代码

5.3 执行时间最多的部分代码

5.4 根据5.2和5.3的结果发现函数process_buffer()耗时占比最大,所以查看process_buffer()函数中调用了哪些函数
5.5 使用可视化工具分析
1.工具;graphviz、Gprof2Dot
2.对main()函数执行产生的word_freq.out进行可视化

浙公网安备 33010602011771号