I am interested in finding least common occurring text in a file.
from collections import Counter
# Load the file and extract the words
lines = open("mobydick.txt").readlines()
words = [ word for l in lines for word in l.rstrip().split() ]
print 'No of words in the file:', len(words)
# Use counter to get the counts
counts = Counter( words )
print 'Least common words:'
for word, count in sorted(counts.most_common()[:-3], key=lambda (word, count): (count, word), reverse=True):
print '%s %s' % (word, count)
How do I limit just 3 words. It prints a bunch.
You are doing slice over list in a wrong way. Just feel the difference
print [1,2,3,4,5][:-3]
[1, 2]
print [1,2,3,4,5][-3:]
[3, 4, 5]
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments