派森练习题:P47 英语单词词频统计

该篇文章介绍了如何使用Python编程分析英文文本,通过`Counter`函数计算文章中单词的出现频率,并按照频率从高到低排序输出出现频率最高的三个单词及其次数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Description

假设你是一名语言学家,你想要分析一篇英文文章的单词使用情况。你需要编写一个程序,读取文章并输出文章中出现频率排名前三的单词及其出现次数。

Format

Input

After a long day at work, I like to come home and relax with a good book, a cup of tea, and some soothing music. Sometimes I also like to watch a movie or play a game on my computer. But no matter what I do, I always try to make sure that I have some time to unwind and recharge before the next day begins.

Output

出现频率最高的三个单词是: a : 5 次 i : 5 次 to : 4 次

注意:单词输出占5个英文字符长度,次数占3个英文字符长度,均是居中对齐。

Samples

输入数据 1

After a long day at work, I like to come home and relax with a good book, a cup of tea, and some soothing music. Sometimes I also like to watch a movie or play a game on my computer. But no matter what I do, I always try to make sure that I have some time to unwind and recharge before the next day begins.

输出数据 1

出现频率最高的三个单词是:
  a  : 5 次
  i  : 5 次
 to  : 4 次

tips:

1.定义字符串txt接收输入的文章内容,并定义一个空字典

2.字符串.split()将英文文章按空格分开,以独个单词的形式进入列表

3.统计列表中的每个数据和次数并组织成字典展示

(此处有很多方法,可使用for循环或者内置函数)

统计列表中每个数据值出现的次数并组织成字典展示

"""
用for循环复杂一点:
# for法一
for i in letter:
    if i not in dic:
        dic[i] = 1
    else:
        dic[i] += 1
print(dic)

# for循环法二
for i in letter:
    dic[i] = dic.get(i, 0) + 1
    
# for循环法三:
for i in set(letter):
    dic[i] = letter.count(i)

并且输出后发现字典并未按字典序排序输出
"""

4.对列表list 进行排序

items.sort(key=lambda x:x[1],reverse=True)_key=lambda x: x[1]_

5.lower函数

Python中的lower()函数是一个常用字符串函数,可以将指定字符串数据列内容转化为小写字符

6.python指定长度输出

python3.5指定长度输出_python打印固定长度_我心依依旧的博客-CSDN博客

代码:

txt = input()
lt = txt.split(" ")
dic = {}
# 内置函数Counter 得到统计好每一个单词和对应出现次数的字典
from collections import Counter
dic = Counter(lt)
# 将刚刚的字典转化为列表并反向排序
sort_lt = sorted(dic.items(), key=lambda x: x[1], reverse = True)
print("出现频率最高的三个单词是:")
for letter in sort_lt[:3]:
    # 单词输出占5个英文字符长度,次数占3个英文字符长度,均是居中对齐。
    # lower函数将所有的字母转换为小写
    print(f"{letter[0].lower():^5}:{letter[1]:^3}次")

纯享版:

txt = input()
lt = txt.split(" ")
dic = {}
from collections import Counter
dic = Counter(lt)
sort_lt = sorted(dic.items(), key=lambda x: x[1], reverse=True)
print("出现频率最高的三个单词是:")
for letter in sort_lt[:3]:
    print(f"{letter[0].lower():^5}:{letter[1]:^3}次")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值