利用collections中的Counter来统计一篇文章中出现次数最多的单词:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Created on 4/21/16
@author: Jiezhi.G@gmail.com
Blog: jiezhi.github.io
Reference: https://docs.python.org/2/library/collections.html#counter-objects
"""
import re
from collections import Counter
file_path = '/Users/jiezhi/Downloads/Scenes from a Courtesan_s Life.txt'
words = re.findall(r'\w+', open(file_path).read().lower())
print Counter(words).most_common(100)
可以得到结果:
[('the', 12405), ('of', 6185), ('to', 5939), ('a', 4931), ('and', 4601), ('in', 3568), ('you', 2759), ('he', 2283), ('is', 2253), ('i', 2224), ('that', 1993), ('as', 1837), ('his', 1834), ('for', 16