统计字符串中每个单词出现的个数和频率----四种方法

’’***'统计每个单词出现的个数(三种方法*
第一种如下:(最简单的方式**)**
‘’’**

sentance = 'I can because i think i can '
#切片分隔成列表序列,用列表推导式表达
rresult = {word: sentance.split ().count ( word ) for word in set ( sentance.split () )}
print ( rresult )
print ( (sentance.split ()) )

统计每个单词出现的个数(第二种)–字典方法(也是比较常见的一种方式)

def word_amount(sentance):
    split_str = sentance.split ()
    dict_new = {}.fromkeys ( split_str, 0 )
    for word_name in split_str:
        if word_name not in dict_new.keys ():
            dict_new[word_name] = 1
            print ( '1' )
    else:
        dict_new[word_name] += 1
return dict_new


if __name__ == "__main__":
    sentance = ' i think i can and can do well'
    print ( word_amount ( sentance ) )

第三种方法:****(引用模块,学会使用一些常见的模块)

from collections import Counter

str0 = 'I can because i think i can'
counts = Counter ( str0.split () )
print ( counts )

还有第四种方法,就是__len__ 和__getitem__,(置字典方法和魔术方法的结合)较难,不推荐,以后深造的时候可以多学学

class Countlist:
    def __init__(self,*args):
        self.values = [a for a  in args]
        self.count ={}.fromkeys(range(len(self.values)),0)
    def __len__(self):
        return len(self.values)
    def __getitem__(self, a):
        self.count[a] += 1
        return self.values[a]


c1 = Countlist(1,3,3,5,7,9)
c2 = Countlist(2,4,6,8,10)
c1[2]
c1[3] + c1[2]
print(c1.values[2])
print(c1.count)
print(c1.values)

结束

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值