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

代码实现:

text = input().lower() # 将输入的英文转换为小写
words = text.split() # 将英文按空格分割成单词
word_count = {} # 定义一个空字典,用于存储每个单词出现的次数
for word in words:
    if word in word_count:
        word_count[word] += 1 # 如果单词已经在字典中出现过,则将其出现次数加 1
    else:
        word_count[word] = 1 # 如果单词是第一次出现,则将其出现次数设置为 1
# 将字典按出现次数从大到小排序,取前五个
top_words = sorted(word_count.items(), key=lambda x: x[1], reverse=True)[:5]
print(top_words) # 输出前五个单词及其出现次数

代码解释:

  1. text = input().lower(): 使用 input() 函数获取用户输入的英文文本,并使用 lower() 方法将其转换为小写字母,方便后续进行大小写不敏感的统计。
  2. words = text.split(): 使用 split() 方法将英文文本按空格分割成单词列表。
  3. word_count = {}: 定义一个空字典 word_count,用于存储每个单词出现的次数。字典的键是单词,值是该单词出现的次数。
  4. for word in words:: 遍历 words 列表中的每个单词。
  5. if word in word_count:: 如果当前单词 word 已经在字典 word_count 中存在,则将其对应的值(出现次数)加 1。
  6. else:: 如果当前单词 word 不在字典 word_count 中,则将其添加进字典,并将其出现次数设置为 1。
  7. top_words = sorted(word_count.items(), key=lambda x: x[1], reverse=True)[:5]: 使用 sorted() 函数对字典 word_count 按出现次数(值)从大到小排序,并使用 [:5] 切片操作取前五个单词及其出现次数。
  8. print(top_words): 打印输出前五个单词及其出现次数。

总结:

本代码利用 Python 的字典数据结构来统计单词出现次数,并使用排序和切片操作获取出现次数排名前五的单词。这是一种简单高效的统计单词频率的方法。

Python 英文单词统计:输出出现次数排名前五的单词

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

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