python 小编程练习——统计字符串中每个单词的词频并返回词频最大的单词,若词频相等,则返回按首字母排序后的第一个单词

为了忘记,写一遍就练习一遍~

import numpy as np
def most_frequent(s):
    word_list = s.split(' ')
    print(word_list)
    new_list = []
    count = []
    for w in word_list:
        if w not in new_list:
            new_list.append(w)
    print(new_list)
    new_list = np.sort(new_list)
    print(new_list)
    for w in new_list:
        count.append(word_list.count(w)) 
    print(count)
    inx = count.index(max(count))
    print(new_list[inx])
    return new_list[inx]
s = 'I scream you scream we all scream for ice cream'
most_frequent(s)

在这里插入图片描述

s = 'I love you !'
most_frequent(s)

在这里插入图片描述
没有添加注释,请谅解~

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值