个人项目(词频统计及其效能分析)

1. 博客开头给出自己的基本信息,格式建议如下:
  学号:2017*****7212;
  姓名:张佳欢;
  码云项目仓库:https://gitee.com/zhangjiahuan123456/word_frequency/tree/SE7212
2. 程序分析,对程序中的四个函数做简要说明。要求附上每一段代码及对应的说明。
首先声明编码方式和导入string模块中的punctuation方法

# -*- coding: UTF-8 -*-
from string import punctuation

1.读取文件函数--打开文件读入缓冲区并关闭文件

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

2.数据处理--去除字符串中的符号将单词分割并读入字典。

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

3.输出Top10结果--遍历字典并输出Top10的单词

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)

4.导入argparse库用于解析命令行数据,依次执行函数

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运行代码
结果如下,输出了词频Top10的单词和次数:

3. 简单性能分析并改进、提交代码
使用cProfile进行性能分析
python -m cProfile word_freq.py Gone_with_the_wind.txt
测试结果如下图(由于测试数据太多,只列举截图了关键信息,耗时最长,调用最多次数的函数):




:

4. 总结反思

在本次课后作业三词频统计及其效能分析中,效能是一个程序性能的决定性表现,今后要更多的学习python 相关知识,在这次作业中,得到同学们的帮助,很快的解决了问题所在,可见团队重要性。主动学习,争取更高效的完成任务。

原文地址:https://www.cnblogs.com/zhangjiahuan/p/10637510.html