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]
least_common = counts.most_common()[-3:]
just move the the :
for word, count in counts.most_common()[-3:]
print '%s %s' % (word, count)
and as @Joran commented, you don't need to sort the result of most_common()
since it's already ordered.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.