I made a function to make a dictionary out of the words in a file and the value is the frequency of the word, named read_dictionary. I'm trying to now make another function that prints the top three words of the file by count so it looks like this: "The top three words in fileName are: word : number word : number word : number"
This is what my code is:
def top_three_by_count(fileName):
freq_words = sorted(read_dictionary(f), key = read_dictionary(f).get,
reverse = True)
top_3 = freq_words[:3]
print top_3
print top_three_by_count(f)
You can use collections.Counter
.
from collections import Counter
def top_three_by_count(fileName):
return [i[0] for i in Counter(read_dictionary(fileName)).most_common(3)]
Actually you don't need the read_dictionary()
function at all. The following code snippet do the whole thing for you.
with open('demo.txt','r') as f:
print Counter([i.strip() for i in f.read().split(' ')]).most_common(3)
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.