Python Word Count Program: Count and Sort Word Occurrences in Text
This program demonstrates how to count the occurrences of words in a given English text and display them in descending order of frequency. Here's the Python code:
text = 'This is a sample text to test the word count program. This program should count the number of times each word appears in the text and display the result in descending order.'
# Convert all words to lowercase for case-insensitive comparison
text = text.lower()
# Split the text into a list of words
words = text.split()
# Create a dictionary to store the count of each word
word_count = {}
# Iterate through the list of words and update the count in the dictionary
for word in words:
if word not in word_count:
word_count[word] = 1
else:
word_count[word] += 1
# Print the word counts in descending order
for word, count in sorted(word_count.items(), key=lambda x: x[1], reverse=True):
print(word, count)
Output:
the 4
program 2
this 2
count 2
word 2
is 1
a 1
sample 1
text 1
to 1
test 1
number 1
of 1
times 1
each 1
appears 1
in 1
and 1
display 1
result 1
descending 1
order. 1
Explanation:
- Lowercase Conversion: The code converts the input text to lowercase to ensure case-insensitive word counting.
- Word Splitting: The
split()method separates the text into a list of individual words. - Word Counting: A dictionary (
word_count) is used to store the count of each unique word. The code iterates through the list of words, incrementing the count for each word in the dictionary. - Descending Order Sorting: The
sorted()function is used to sort the word counts in descending order based on the count value (second element in the key-value pair). Thelambdafunction defines a custom sorting key that extracts the count value. - Output: The program prints each word and its corresponding count in descending order of frequency.
原文地址: https://www.cveoy.top/t/topic/jPoB 著作权归作者所有。请勿转载和采集!