学Python的入门(3)——使用字典统计文本字数

  import string #需要用到这个包来去掉符号
  with open ('E:/learning/python/script/Walden.txt',encoding='utf-8','r') as text:  #刚下载的txt有时候打不开,不要用到encoding来打开
    words = [raw_word.strip(string.punctuation).lower() for raw_word in text.read().split()]
    words_index = set(words) # 生成唯一索引
    counts_dict = {index:words.count(index) for index in words_index}
  for word in sorted(counts_dict,key=lambda x:count_dict[x],reverse=True):
    print('{}:{} times' .format(word,counts_dict[word]))
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容