97.6k views
5 votes
Write a program that prints the distinct words in its input sorted into decreasing order of frequency of occurrence. Precede each word by its count.

User Jomara
by
8.0k points

1 Answer

6 votes

Final answer:

The question requires writing a program to sort words by descending frequency. A Python script using the Counter class can accomplish the task efficiently. Words are counted, sorted, and printed with their frequencies.

Step-by-step explanation:

The question pertains to programming and requires a script to process text input, count the frequency of distinct words, and then display them in descending order, prefixed by their frequency count. A common approach to this problem would be to use a dictionary data structure to keep track of word counts and then sort the entries based on those counts.

from collections import Counter

def get_word_frequencies(text):
words = text.split()
counter = Counter(words)
return counter.most_common()

def print_word_frequencies(frequencies):
for word, count in frequencies:
print(f'{count} {word}')

input_text = 'your text here'
frequencies = get_word_frequencies(input_text)
print_word_frequencies(frequencies)

This Python program uses the Counter class from collections to easily count occurrences and the most_common() method to sort them. It defines two functions: one for getting word frequencies and another for printing out frequencies alongside their respective words.

User Lebert
by
7.3k points
Welcome to QAmmunity.org, where you can ask questions and receive answers from other members of our community.