198
社区成员




# filename: word_freq.py
# 注意:代码风格
from string import punctuation
def process_file(dst): # 读文件到缓冲区
try: # 打开文件
_________(1)_________
except IOError, s:
print s
return None
try: # 读文件到缓冲区
_________(2)_________
except:
print "Read File Error!"
return None
________(3)__________
return bvffer
def process_buffer(bvffer):
if bvffer:
word_freq = {}
# 下面添加处理缓冲区 bvffer代码,统计每个单词的频率,存放在字典word_freq
__________________
__________________
_______(4)______
__________________
__________________
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)
python word_freq.py Gone_with_the_wind.txt
实验: 性能评估--词频统计软件:基于Python 编写: word_freq.py
A、使用 cProfile 进行性能分析。
用法:
python -m cProfile word_freq.py filescounted.txt [| grep word_freq.py]
python -m cProfile word_freq.py Gone_with_the_wind.txt | grep word_freq.py
可视化操作
需要安装:graphviz , "pip install graphviz"; 参考使用cProfile分析Python程序性能:链接
下载转换 dot 的 python 代码 gprof2dot 官方下载,下载完了,解压缩,将『gprof2dot.py』 copy 到当前分析文件的路径,或者你系统 PATH 环境变量设置过的路径。
执行下述步骤:
1. 性能分析:``` python -m cProfile -o result.out -s cumulative word_freq.py Gone_with_the_wind.txt``` ;分析结果保存到 result.out 文件;
2. 转换为图形;gprof2dot 将 result.out 转换为 dot 格式;再由 graphvix 转换为 png 图形格式。 命令:```python gprof2dot.py -f pstats result.out | dot -Tpng -o result.png```
转换得到图如下:
指出寻找执行时间、次数最多的部分代码,尝试改进。
PS: 能够改进 4分,只进行性能评估(2分)
一个能够可视化性能监控结果的博客:使用cProfile分析Python程序性能
B、代码行级别性能分析工具:line_profiler ——一个能针对代码行级别的性能分析工具。
参考博客:python模块-cProfile和line_profiler(性能分析器)
###(1)程序分析,对程序中的四个函数做简要说明 (3分)
###(2)代码风格说明。 (2分)
网上检索 Python 代码风格规范,选取其中一条,对照程序 word_freq.py 的对应部分加以说明。
Python 代码强调变量命名要*****,例如程序中第 **~ ** 行 代码:
```
print "Read File Error!" # 这里只是举例
```
###(3)程序运行命令、运行结果截图 (2分)
###(4)性能分析结果及改进 (3分)
···
ncalls:表示函数调用的次数;
tottime:表示指定函数的总的运行时间,除掉函数中调用子函数的运行时间;
percall:(第一个percall)等于 tottime/ncalls;
cumtime:表示该函数及其所有子函数的调用运行的时间,即函数开始调用到返回的时间;
percall:(第二个percall)即函数运行一次的平均时间,等于 cumtime/ncalls;
filename:lineno(function):每个函数调用的具体信息;
···