您当前的位置: 首页 >  彭世瑜 Python

Python编程:使用defaultdict统计词频

彭世瑜 发布时间:2019-02-21 15:36:08 ,浏览量:1

# -*- coding: utf-8 -*-

# 要统计的词
words = ["腾讯", "百度", "阿里巴巴", "百度", "阿里巴巴"]


# 方式一:使用dict方式
counter1 = {}
for word in words:
    counter1[word] = counter1.get(word, 0) + 1

print(counter1)
# {'腾讯': 1, '百度': 2, '阿里巴巴': 2}


# 方式二:使用defaultdict
from collections import defaultdict

counter2 = defaultdict(lambda: 0)

for word in words:
    counter2[word] += 1

print(counter2)
# defaultdict(,
# {'腾讯': 1, '百度': 2, '阿里巴巴': 2})

参考: python中defaultdict方法的使用

关注
打赏
1688896170
查看更多评论

彭世瑜

暂无认证

  • 1浏览

    0关注

    2727博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文
立即登录/注册

微信扫码登录

0.0591s