This is a much more direct way to count the frequency of words in a file:
from collections import Counter def count_words_in_file(file_path): with open(file_path) as f: return Counter(f.read().split())
Example:
>>> count_words_in_file('C:/Python27/README.txt').most_common(10) [('the', 395), ('to', 202), ('and', 129), ('is', 120), ('you', 111), ('a', 107), ('of', 102), ('in', 90), ('for', 84), ('Python', 69)]
source share