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指定长度输出
代码:
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}次")