利用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', 1639), ('was', 1556), ('with', 1395), ('it', 1387), ('said', 1376), ('had', 1366), ('on', 1337), ('at', 1303), ('have', 1267), ('her', 1250), ('by', 1244), ('be', 1230), ('s', 1184), ('this', 1158), ('she