课后做业3:我的项目(词频统计及其效能分析)

1.我的信息

  • 学号:2017XXXXX7242
  • 姓名:闻绍天
  • 词频统计及其效能分析仓库:仓库地址

2.程序分析

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

    f.close()

    return bvffer

process_file函数的做用是,经过传入dst参数,dst是文件的名称+后缀名,经过文件打开,读取,最终返回dst文件的字符串形式bvffer。python

def process_buffer(bvffer):
    if bvffer:
        word_freq = {}
        # 下面添加处理缓冲区 bvffer代码,统计每一个单词的频率,存放在字典word_freq

        # 全变小写,解决大小写单词不一样问题
        bvffer = bvffer.lower()
        # 把除了小写字母和空白字符,的其余字符,替换成空字符
        bvffer = re.sub('[^a-z \s]', '', bvffer)
        # 把空白字符都换成空格
        bvffer = re.sub('\s', ' ', bvffer)

        # 经过切空格把每一个单词分开成一个list
        word_list = bvffer.split(' ')

        # 经过循环,将单词做为key存到word_list字典中,并将value初始值设为0
        for item in word_list:
            if not item:
                continue
            word_freq[item.strip()] = 0

        # 经过循环,判断是否在字典中,若在字典中,value+1
        for item in word_list:
            if not item:
                continue
            word_freq[item] = word_freq[item] + 1
        return word_freq
  • process_buffer函数传入的参数是process_file函数返回的bvffer字符串git

  • 将bvffer字符串进行,小写,去除除了小写字母和空白字符的其余字符,把空白字符换成空格函数

  • 以空格分隔,使用split(),经过循环把单词和出现次数放到字典word_freq中性能

  • 返回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)

output_result函数传入上面的字典word_freq参数,输出词频前10的单词spa

运行结果

  • 大文件:Gone_with_the_wind.txt

python word_freq.py Gone_with_the_wind.txt3d

  • 小文件:A_Tale_of_Two_Cities.txt

python word_freq.py A_Tale_of_Two_Cities.txtcode

### 3.简单性能分析并改进、提交代码blog

python -m cProfile word_freq.py Gone_with_the_wind.txtip

总共有442597次函数调用,程序总共耗时0.464秒

其中process_buffer占用了,0.408秒

执行次数最多的是strip函数

问题

  1. word_freq[item.strip()] = 0的strip多余,以前已经经过正则,去掉了空白字符
  2. 在process_buffer函数中,创建word_list字典使用了两次for循环

改进

  1. 去掉strip()函数

  2. 改为一个for循环

for item in word_list:
    if not item:
        continue
    if item in word_freq:
        word_freq[item] = word_freq[item] + 1
    else:
        word_freq[item] = 1

总结

  • 经过此次的词频统计案例,复习了python的文件读写,字符串处理等操做。

  • 更加深刻地学习使用了git

  • 熟悉了效能分析的基本流程和方法

相关文章
相关标签/搜索