Python读书笔记-每日篇-20190301|单词统计

问题描述: 任一个英文的纯文本文件,统计其中的单词出现的个数。

需求分析:

  1. 数据通过文件读取
  2. 读取文件中的单词
  3. 统计每个单词的个数

代码编写:

'''
Created on 2019年3月1日

@author: Administrator
'''
import re
import collections

def word_list(filename):
    try:
        with open(filename,"r") as file:
            file_content = file.read()
    except Exception as e:
        print("FIle[%s] read Error!"%filename,e)
    else:
        pattern = re.compile(r'\W+')
        words = pattern.split(file_content)
        return words

def word_counter(filename):
    words = word_list(filename)
    word_collection = collections.Counter(words)
    return word_collection

if __name__ == "__main__":
    print(word_list("d:\\Magnets.txt"))
    word_colletion = word_counter("d:\\Magnets.txt")
    for word,word_count in word_colletion.most_common(18):
        print(f'{word:<20}:{word_count}')

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值