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

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

作者: rickd83 | 来源:发表于2017-10-09 15:24 被阅读0次
      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]))

    相关文章

      网友评论

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

          本文链接:https://www.haomeiwen.com/subject/sukpyxtx.html