2018-08-31第4个小程序:统计文章中单词出现次数

import string
path = "C://Users/seewo.chen/Downloads/Walden.txt"
newpath = "C://Users/seewo.chen/Downloads/Walden_new.txt"
file = open(path, encoding='gb18030', errors='ignore')
file_new = open(newpath, 'w')
file_new.write(file.read())
file.close()
file_new.close()
with open(newpath, 'r') as text:
    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: counts_dict[x], reverse=True):
        print('{}--{} times'.format(word, counts_dict[word]))
image.png

你可能感兴趣的:(2018-08-31第4个小程序:统计文章中单词出现次数)