「Python」4-5

编写一个函数,统计一下文章中出现的单词频率,存在一个字典中。字典的键是单词,值为单词出现的次数。注意,需将所有单词都转换为小写单词进行统计,文章中出现的的所有标点符号,均不能统计在字典中,包括: , " ' / ? ;  =。

从键盘接收一段英文文章,并将词频统计的结果按照单词字母排序升序输出在屏幕上。注意,每个单词词频信息占一行,输出的格式为:  单词 : 词频,“:”前后各有一个空格。

example:

input:

Once upon a time, there lived a monkey in the woods. The monkey climbed up the tree and looked down at the river everyday.

output:

a : 2

and : 1

at : 1

climbed : 1

down : 1

everyday : 1

in : 1

lived : 1

looked : 1

monkey : 2

once : 1

river : 1

the : 4

there : 1

time : 1

tree : 1

up : 1

upon : 1

woods : 1

注意,因为dict无序,想按照顺序输出,不能用sorted,可以将字典中的key拿出来,放在list里进行排序,并通过排好序的list打印输出字典中的值。

def wordcount(s):

    for i in ''',?/":;=.''':
        s=s.replace(i,'')

    s=s.lower()
    s=s.split()
    s=sorted(s)
    for i in s :
        if i not in dic.keys():
            dic[i]=1
        else:
            dic[i]+=1

s = input()
dic = {}
wordcount(s)
for i in dic.keys():
    print(f"{i} : {dic[i]}")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值