如何统计一篇文章里,每个单词都出现了多少次?

使用python实现统计一个文章里的单词的出现次数。

如果使用的是txt文件,可能需要用notepad++来载入,更改编码为utf-8.

# -*- coding:utf-8 -*-
# auth : sunchao
# 此程序的目的是提取文档中的全部单词,并统计单词出现的次数
import string

path = r'D:\学习文档\PYTHON\魔力手册\Walden.txt'
with open(path, '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}                        # 通过index写入字典

    for word in sorted(counts_dict, key=lambda x: counts_dict[x], reverse=True):              # 通过字典进行字数统计
        print('{}-{} times'.format(word, counts_dict[word]))

posted on 2015-12-17 16:02  我家有个小豌豆  阅读(1572)  评论(1编辑  收藏  举报

导航