英文文章的词频统计

本文分享了一种不使用value_counts()函数进行词频统计的方法。通过将文件内容转换为字符串,并利用Python内置函数处理,实现了词频统计。同时,介绍了如何使用get()方法简化代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天去面试,被问到如何实现词频统计,因为之前都是直接调用value_counts()函数统计,在被要求不用该函数实现统计,一紧张就卡壳了,回到家大概自己想了一下,怎么一步步复现。

实现的方法有多种,我才用的办法是先把文件处理成string类型,然后string处理函数

#读入文件并处理成文本
def read_file(text_file):
    string_for_count=[]
    with open(text_file) as wf:
        for line in wf:
            string_for_count.append(line)
    return ''.join(string_for_count)   

随后定义文本中词语的词频统计

#统计词频
def word_counts(string):
    string_list = string.replace('\n','').lower().split(' ')
    count_dic = {}
    for item in string_list:
        if item in count_dic.keys():
            count_dic[item] += 1
        else:
            count_dic[item] = 1
    if ' ' in count_dic:
        count_dic.pop('') #删除空格
    count_list = sorted(count_dic.iteritems(),key=lambda x: x[1],reverse=True)
    return count_list

写的仓促,仅仅纪念惨淡的一次面试,以及渣渣的学习之路

在复习《机器学习实战》的时候,对于第二部分统计词频,获取到了使代码更简洁的表达方式,如下:

def word_counts(string):
    string_list = string.replace('\n','').lower().split(' ')
    count_list = {}
    for item in string_list:
        count_list[item] = count_list.get(item,0)+1
    if ' ' in count_list:
        count_list.pop('') #删除空格
    count_list = sorted(count_list.items(),key=lambda x: x[1],reverse=True)
    return count_list
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值