Python 统计英文单词出现次数并排序 - 前五名

本文将介绍如何使用 Python 代码统计一段英文文本中每个单词出现的次数,并输出出现次数排名前五的单词和次数。

输入输出样例

输入:

'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)]

解题思路

  1. 将输入的英文字符串转换为小写,以便统一处理;
  2. 将字符串按照空格切分成单词列表;
  3. 遍历单词列表,统计每个单词出现的次数,使用字典来存储;
  4. 对字典按照值(即单词出现次数)进行排序,取前五个元素。

代码实现

# 输入英文字符串,转换为小写
text = input().lower()

# 将字符串按照空格切分成单词列表
words = text.split()

# 统计每个单词出现的次数,使用字典来存储
word_count = {}
for word in words:
    if word in word_count:
        word_count[word] += 1
    else:
        word_count[word] = 1

# 对字典按照值(即单词出现次数)进行排序,取前五个元素
top_words = sorted(word_count.items(), key=lambda x: x[1], reverse=True)[:5]

# 输出结果
print(top_words)

注意事项

  • 注意单词的大小写统一问题,将所有单词转换为小写或大写;
  • 在统计单词出现次数时,可以使用 collections.Counter 类来简化代码。
Python 统计英文单词出现次数并排序 - 前五名

原文地址: https://www.cveoy.top/t/topic/oskq 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录