用python实现文件的词频统计

"""
@name : 词频统计
@author : huangshilong
@projectname : file_opreat
"""
def deal_text():
    # 用上下文管理器打开文件
    with open('Walden.txt','r+') as fp:
        # 读取文件内容
        text = fp.read()
        # 消除大小写
        text=text.lower()
        # 消除特殊字符
        # sub_post = re.sub(u"([^\u4e00-\u9fa5\u0030-\u0039\u0041-\u005a\u0061-\u007a])", ' ', post)
        for ch in '!"#$%&()*+,-./:;<=>?@[\\]^_{|}.~’‘':
            text = text.replace(ch, "")
        # 将文本分割成单个单词
        text = text.split()
        # 返回文本列表
        return  text
def count_text():
    # 调用处理文本的函数
    txt = deal_text()
    # 创建一个单词字典
    word_dict ={}
    # 写入单词元素及出现次数
    for item in txt:
        if item not in word_dict:
            word_dict[item] = 1
        else:
            word_dict[item]+=1
    #得到出现次数前十的一个列表
    list_top10_word =[]
    for item in word_dict:
         list_top10_word.append(word_dict[item])
    # 通过列表的sort方法对列表进行排序,方便取最后的出现次数最多的十个元素
    list_top10_word.sort()
    list_top10_word=list_top10_word[-1:-11:-1]
    # 使用字典生成式生成次数前十的单词的字典,并输出
    dict_top10_word = {key:word_dict[key] for key in word_dict if word_dict[key] in list_top10_word}
    print(dict_top10_word)
count_text()

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值