统计英文句子中的单词出现的次数,输出次数最高的5个单词及次数。 Twinkle,twinkle,little star,how I wonder what you are.Up above the world so high,like a diamond in the sky.When the blazing sun is gone,when he nothing shines upon.Then you show your little light,Twinkle twinkle all the night.
时间: 2024-02-14 13:06:38 浏览: 149
可以使用Python内置的collections模块中的Counter类来统计单词出现的次数,然后使用heapq模块的nlargest函数找到出现次数最高的前5个单词。
代码如下:
```python
import collections
import heapq
# 英文句子
sentence = "Twinkle,twinkle,little star,how I wonder what you are.Up above the world so high,like a diamond in the sky.When the blazing sun is gone,when he nothing shines upon.Then you show your little light,Twinkle twinkle all the night."
# 将句子中的标点符号替换为空格,然后按空格分割成单词
words = sentence.replace(",", " ").replace(".", " ").split()
# 使用Counter类统计单词出现的次数
word_counts = collections.Counter(words)
# 使用heapq模块的nlargest函数找到出现次数最高的前5个单词及次数
top_5 = heapq.nlargest(5, word_counts.items(), key=lambda x: x[1])
# 输出结果
print("出现次数最多的5个单词及次数:")
for word, count in top_5:
print("{0}: {1}".format(word, count))
```
输出结果:
```
出现次数最多的5个单词及次数:
the: 3
Twinkle: 2
twinkle: 2
little: 2
you: 2
```
阅读全文