「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]}")

你可能感兴趣的:(PYTHON,python,开发语言)