软工作业2 (词频统计)

词频分析报告

1.程序分析

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

功能:打开对应文件,将文件存入对应缓冲区bvffer

# 统计词频函数
def process_buffer(bvffer):
    if bvffer:
        word_freq = {}  # 新建一个空字典word_freq
        # 下面添加处理缓冲区 bvffer代码,统计每个单词的频率,存放在字典word_freq
        for word in bvffer.split():  # .split()函数将bvffer切片
            if word not in word_freq:
                word_freq[word] = 0
            word_freq[word] += 1
        return word_freq

函数的参数为上一个函数产生的bvffer
构建空字典word_freq 将bvffer中的数据通过split()进行切片
将单词存入字典中 返回值为字典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)

sorted()将字典中的单词按照词频进行排序
输出对应的前十个单词

def main():
    dst = "F:/Python_Class/Gone_with_the_wind.txt"
    bvffer = process_file(dst)
    word_freq = process_buffer(bvffer)
    output_result(word_freq)

在main函数中调用前三个函数,读取项目中的Gone_with_wind.txt
统计前十个单词

2.代码风格说明

函数名: 全小写+下划线式驼峰 示例:this_is_var

process_file
process_buffer
output_result

变量名:尽量体现变量的数据类型和具体意义
bvffer word_freq sorted_word_freq item
dst(改为file-path更加直观)

在使用# 的时候,# 号后面要空一格
在行内注释的时候,中间应该至少加两个空格

# 统计词频函数
def process_buffer(bvffer):
    if bvffer:
        word_freq = {}  # 新建一个空字典word_freq
        # 下面添加处理缓冲区 bvffer代码,统计每个单词的频率,存放在字典word_freq
        for word in bvffer.split():  # .split()函数将bvffer切片
            if word not in word_freq:
                word_freq[word] = 0
            word_freq[word] += 1
        return word_freq

导入总应该放在文件顶部,位于模块注释和文档字符串之后,模块全局变量和常量之前。

if __name__ == "__main__":
    import cProfile
    import pstats
    cProfile.run("main()" , filename="result.out")
    p = pstats.Stats('result.out')  # 创建Stats对象
    p.sort_stats('calls').print_stats(10)  # 按调用次数排序,打印前10函数的信息
    p.strip_dirs().sort_stats("cumulative", "name").print_stats(10)  # 按运行时间和函数名进行排序,打印前10行函数的信息
    p.print_callees("process_buffer")  # 查看process_buffer()函数中调用的函数

应放在文件顶部

3.程序运行命令、运行结果截图

Gone_with_wind.txt 中词频前十单词截图

在这里插入图片描述

函数运行时间截图

在这里插入图片描述
在这里插入图片描述

4.性能分析结果及改进

执行次数最多代码
            sorted_word_freq = sorted(word_freq.items(), key=lambda v: v[1], reverse=True)
时间最长
def process_buffer(bvffer):
    if bvffer:
        word_freq = {}                     #新建一个空字典word_freq
        # 下面添加处理缓冲区 bvffer代码,统计每个单词的频率,存放在字典word_freq
        for word in bvffer.split():      #.split()函数将bvffer切片
            if word not in word_freq:
                word_freq[word]=0
            word_freq[word]+=1
        return word_freq

系统存在的问题

英文文章中,句首的单词要求大写,而程序的函数中只是用split函数简单进行分割。从而导致句首的单词被视为一个新的单词,使得结果产生很大的误差
应将process_buffer函数进行改进 使用.lower()将句首的大写字母改为小写
使用正则表达式吧字母和空格以外的符号去除 将去除的bvffer存入new_bvffer中

改进后的函数process_buffer如下

def process_buffer(bvffer):
    if bvffer:
        new_bvffer = re.sub(r'[^A-Za-z]', ' ', bvffer)  # 使用正则表达式把除了字母和空格以外的符号都去除
        words = new_bvffer.split()
        word_freqs = {}
        for word in words:
            if word.lower() in word_freqs:
                word_freqs[word.lower()] = word_freqs[word.lower()] + 1
            else:
                word_freqs[word.lower()] = 1
    return word_freqs

统计大写单词后的统计结果

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

羲和忆望舒

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值