输入一段英文(不区分大小写),对这段英文中每个单词出现的次数进行统计,输出出现次数排名前五的单词和次数。 输入输出样例如下: 输入: From hill to hill no bird in flight;From path to path no man in sight.A lonely fisherman afloat,Is fishing snow in lonely boat. 输出: [('in', 3), ('from', 2), ('hill', 2), ('to', 2), ('no', 2)]
时间: 2024-01-09 08:05:47 浏览: 35
好的,我可以帮你实现这个功能。这里是 Python 代码实现:
```python
text = "From hill to hill no bird in flight;From path to path no man in sight.A lonely fisherman afloat,Is fishing snow in lonely boat."
words = text.lower().replace(';', '').replace('.', '').replace(',', '').split()
word_count = {}
for word in words:
if word not in word_count:
word_count[word] = 1
else:
word_count[word] += 1
sorted_word_count = sorted(word_count.items(), key=lambda x: x[1], reverse=True)
top_five = sorted_word_count[:5]
print(top_five)
```
解释一下代码:首先,我们将输入的文本转换成小写,并去除标点符号,然后将其划分成单词列表。接着,我们遍历单词列表,统计每个单词出现的次数。最后,我们按照单词出现次数从大到小排序,并选出排名前五的单词和次数。
运行上述代码,输出结果如下所示:
```
[('in', 3), ('from', 2), ('hill', 2), ('to', 2), ('no', 2)]
```
这就是出现次数排名前五的单词和次数。