0% found this document useful (0 votes)
9 views

Lab Program 6

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Lab Program 6

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 1

6. Develop a program to print 10 most frequently appearing words in a text file.

[Hint: Use dictionary


with distinct words and their frequency of occurrences. Sort the dictionary in the reverse order of
frequency and display dictionary slice of first 10 items]

def count_words(filename):

dict = {}

# Read the file and count the occurrences of each word

with open(filename, 'r') as file:

words = file.read().lower().split()

for word in words:

dict[word] = dict.get(word, 0) + 1

return dict

def top_10_words(dict):

# Sort the dictionary by value in descending order

sorted_words = sorted(dict.items(), key=lambda x: x[1], reverse=True)

# Print the top 10 words and their frequencies

print("Top 10 most frequently appearing words:")

for word, count in sorted_words[:10]:

print(f"{word}: {count}")

filename = input("Enter the file name")

# Count and print the words in the file

dict = count_words(filename)

top_10_words(dict)

You might also like