编写代码统计英文中单词出现的次数并按降序输出
以下是Python代码实现:
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."
# 将所有单词转换为小写,以便进行比较
text = text.lower()
# 将文本分割为单词列表
words = text.split()
# 创建一个字典来存储每个单词出现的次数
word_count = {}
# 遍历单词列表并更新字典中的计数器
for word in words:
if word not in word_count:
word_count[word] = 1
else:
word_count[word] += 1
# 按降序输出单词计数
for word, count in sorted(word_count.items(), key=lambda x: x[1], reverse=True):
print(word, count)
输出:
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
``
原文地址: https://www.cveoy.top/t/topic/clwF 著作权归作者所有。请勿转载和采集!